创建一个新 的线程,其功能对应进程中的fork函数,如果成功返回0,不成功返回一个错误的号码
展开代码int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg);
- pthread_t *thread:这是一个指向pthread_t类型变量的指针,用于存储新创建的线程的标识符。当函数成功时,这个变量会被设置为新线程的线程 ID。
- const pthread_attr_t *attr:这是一个指向const pthread_attr_t结构的指针,用于设置线程的属性。如果你不需要设置特殊的属性,可以传递NULL。
- void *(*start_routine) (void *):这是一个指向函数的指针,该函数将成为新线程的入口点。这个函数应该接受一个void指针作为参数,并返回一个void指针。通常,这个函数不会返回任何值,但在某些情况下,它可能用于线程间的通信。当指定的函数运行完后,则线程就结束了。
- void *arg:设置线程主函数的参数,如果没有,这设置为NULL。你可以通过这个参数向新线程传递数据。
等待执行的线程,并接受子进程返回的状态
展开代码int pthread_join(pthread_t thread, void **retval);
- pthread_t thread:这是要等待的线程的标识符。这个标识符通常是在调用 pthread_create 函数时返回的。
- void **retval:这是一个指向指针的指针,用于接收子线程的返回值。如果不需要子线程的返回值,可以将这个参数设置为 NULL。
获取当前线程的id,其返回值为Pthread_t类型(线程id类型)
展开代码pthread_t pthread_self(void);
创建线程私有数据pthread_key_t结构
展开代码int pthread_key_create(pthread_key_t *key, void (*destructor)(void*));
- pthread_key_t *key:这是一个指向pthread_key_t类型变量的指针,用于存储新创建的键。在成功调用pthread_key_create后,这个变量将包含新键的标识符。
- void (*destructor)(void*):这是一个函数指针,指向一个析构函数。析构函数在线程退出时自动调用,用于释放与键关联的数据。如果不需要析构函数,可以将此参数设置为NULL。
注意:此处的pthread_key_t结构,可以理解为各个线性中,同名但内容不同的变量
注销线程中的私有数据
展开代码int pthread_key_delete(pthread_key_t key);
写线程私有数据
展开代码int pthread_setspecific(pthread_key_t key, const void *value);
- pthread_key_t key:这是通过pthread_key_create函数创建的线程特定数据键。
- const void *value:这是要与键相关联的值。这个值可以是任何类型的数据,因为void *是一个通用指针类型。
读线程私有数据
展开代码void *pthread_getspecific(pthread_key_t key);
- 第一个参数为指定需要内容的****pthread_key_t变量。此处需要注意,如果pthread_key_t变量的内容为空,则会返回0(NULL)
展开代码#include <stdio.h> #include <stdlib.h> #include <pthread.h> void* child1(){ printf("Child 1 is running\n"); pthread_exit(NULL); } void* child2(){ printf("Child 2 is running\n"); pthread_exit(NULL); } int main() { printf("this is main thread\n"); pthread_t tid1, tid2; int ret; ret = pthread_create(&tid1, NULL, child1, NULL); if (ret != 0) { printf("Error creating tid 1\n"); exit(EXIT_FAILURE); } ret = pthread_create(&tid2, NULL, child2, NULL); if (ret != 0) { printf("Error creating tid 2\n"); exit(EXIT_FAILURE); } pthread_join(tid1, NULL); pthread_join(tid2, NULL); return 0; }

本文作者:zzz
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!