建設(shè)網(wǎng)站寶安區(qū)短視頻營銷推廣方案
0.線程特點(diǎn)
(1).線程共享資源:一個進(jìn)程下的多個線程共享以下資源
? ? ? ? ? ? ? ? 可執(zhí)行的指令
? ? ? ? ? ? ? ? 靜態(tài)數(shù)據(jù)
? ? ? ? ? ? ? ? 進(jìn)程中打開的文件描述符
? ? ? ? ? ? ? ? 當(dāng)前工作目錄
? ? ? ? ? ? ? ? 用戶ID
? ? ? ? ? ? ? ? 用戶組ID
(2).線程私有資源:
? ? ? ? ? ? ? ? 線程ID
? ? ? ? ? ? ? ? PC(程序計數(shù)器)和相關(guān)寄存器
? ? ? ? ? ? ? ? 堆棧
? ? ? ? ? ? ? ? 錯誤號(errno)
? ? ? ? ? ? ? ? 優(yōu)先級
? ? ? ? ? ? ? ? 執(zhí)行狀態(tài)和屬性
一.C函數(shù)創(chuàng)建線程、回收線程、結(jié)束線程
1.創(chuàng)建線程 - pthread_create
功能:
? ? ? ? 創(chuàng)建一個線程,成功時返回(0),失敗時返回錯誤碼(errno)
參數(shù):
? ? ? ? thread: 線程對象
? ? ? ? attr? ? ?: 線程屬性,NULL則表示默認(rèn)屬性
????????void*(*routine)(void*):線程執(zhí)行的函數(shù)
? ? ? ? arg? ? ? :傳遞給線程執(zhí)行函數(shù)的參數(shù)
int pthread_create(pthread_t *thread,const pthread_attr_t *attr,void*(*routine)(void*),void *arg);
????????????????
2.線程回收 - pthread_join
功能:
? ? ? ? 回收線程資源,成功時返回0,失敗返回錯誤碼。
? ? ? ? 調(diào)用線程阻塞直到pthread結(jié)束
參數(shù):
? ? ? ? thread? ?: 線程對象,指定要回收的線程
? ? ? ? retval? ? : 接收線程返回值的地址
int pthread_join(pthread_t thread,void **retval);
3.線程結(jié)束 - pthread_exit
功能:
? ? ? ? 結(jié)束當(dāng)前的線程,釋放該線程的私有資源。
參數(shù):
? ? ? ? retval: 可被其他線程通過 pthread_join 獲取。
void pthread_exit(void *retval);
4.線程創(chuàng)建、回收、結(jié)束,代碼示例
#include <stdio.h>
#include <stdint.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#include <pthread.h>
#include <stdlib.h>
#include <string.h>char message[32] = "Hello World";
void *thread_func(void *arg);int main()
{pthread_t a_thread; //創(chuàng)建線程對象void *result; //用于接收線程返回值int ret;/* 創(chuàng)建線程,綁定線程執(zhí)行函數(shù) */ret = pthread_create(&a_thread,NULL,thread_func,NULL);if(0 != ret){printf("fail to pthread_create\n");exit(-1);}/* 阻塞等待回收線程資源 */pthread_join(a_thread,&result); //將結(jié)果存入resultprintf("result is :%s\n",result);printf("message is :%s\n",message);return 0;
}/* 線程函數(shù) */
void *thread_func(void *arg)
{sleep(1);printf("thread_func has been created\n");strcpy(message,"marked by thread_func\n");/* 結(jié)束線程 */pthread_exit("thank you for waiting for me\n"); //線程結(jié)束返回參數(shù)信息
}