- C语言线程基本函数
学习内容:
线程常用基本函数:
- pthread_create() 创建线程
- pthread_exit() 退出当前线程
- pthread_join() 等待其他线程结束
- pthread_self() 自身线程ID号
- pthread_cancel() 停止其他线程
- pthread_detach() 分离某个线程
学习笔记:
线程使用需要导入对应头文件
- #include
函数原型:
int pthread_create(pthread_t *th,
const pthread_attr_t *attr,
void *(* func)(void *),
void *arg);
pthread_exit() 退出当前线程
函数原型:
void pthread_exit(void *res);
- res 用法见示例代码
函数原型:
int pthread_join(pthread_t th, void **res);pthread_self() 自身线程ID号
函数原型:
pthread_t pthread_self(void);pthread_cancel() 停止其他线程
函数原型:
int pthread_cancel(pthread_t th);pthread_detach() 分离某个线程
函数原型:
int pthread_detach(pthread_t th);
- 如果对某个线程使用了pthread_detach,那么在其他线程中无法使用 pthread_join
#include效果截图#include #include #include #include #define OPEN_DEBUG_MESSAGE #ifdef OPEN_DEBUG_MESSAGE # define D_MES(message) printf(message) #else # define D_MES(message) #endif typedef struct TResultTag TRes; struct TResultTag { char data[20]; int num; }; void *task1_entry(void *param) { TRes *res = (TRes *)param; int i; for(i = 0; i < 10; i++) { printf("task i -> %dn",i); sleep(1); } sprintf(res->data, "task1 id:%lu", pthread_self()); res->num = 520; pthread_exit(param); } int main() { printf("hellon"); // 用于子线程结束后传出返回值 TRes *res = (TRes *)malloc(sizeof(TRes)); if (res != NULL) { pthread_t task1; // 创建线程 if (pthread_create(&task1, NULL, task1_entry, res) != 0) printf("failed in pthread_create n"); sleep(1); // pthread_detach(task1); // 打开该行 pthread_join 会失败 int i; for(i = 0; i < 5; i++) { printf("main i -> %dn",i); sleep(1); } // 等待线程 task1 结束 if (pthread_join(task1, (void **)&res) == 0) // 输出由 task1 传出的返回值 printf("res->data:%snres->:%dn", res->data, res->num); else printf("ERROR: pthread_join"); } else printf("failed in mallocn"); system("pause"); return 0; }
-
不执行pthread_detach()
-
执行pthread_detach()



