第一次尝试使用 pthread,希望对基本的常用函数的用法有个大致了解,能对这些函
数有个大致了解。
pthread 函数
1  | int pthread_create(pthread_t *thread, const pthread_attr_t *attr,  | 
参数 thread 传入一个 pthread_t *,函数调用成功时该参数被设置为所创建线程
的 ID。参数 attr 保存创建线程时所需要的属性。参数 start_routine 为新线程创
建后会执行的函数。arg 会作为 start_routine 的参数传入。
pthread_create()的返回值表示错误码,成功时返回0。
1  | int pthread_join(pthread_t thread, void **retval);  | 
pthread_join()等待一个线程结束,并回收其返回值到retval。
1  | pthread_t pthread_self(void);  | 
pthread_self()用于获取当前线程的 ID。man pthread_self中说这个函数调用问
题成功,我也不清楚为什么。。。
RETURN VALUE
This function always succeeds, returning the calling thread’s ID.
例子
这个例子的作用是向线程传入两个数,在线程中相加后,返回其结果。因为只能传入
一个参数,所以使用了结构体。
1  | 
  | 
编译时需要加上-pthread选项,编译运行如下:
1  | $ clang pthread.c -pthread  | 
References
man pthread_createman pthread_joinman pthread_exitman pthread_selfman pthread_attr_init