线程函数

线程函数

  • 线程创建
#include<pthead.h>
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,  void * (*start_routine)(void *), void * restrict arg);
 
 

attr一般为NULL,采用系统默认属性。

成功返回0,失败返回错误号。

pthread_t无符号整型

pthread库的函数都是通过返回值返回错误号,虽然每个线程都有一个errno,但并不使用它。因此不能调用perror打印错误信息,可先用strerror把返回值(错误码)转化为错误信息再打印。

  • 线程终止

终止线程有三种方法:

1)从线程函数return。

2)调用pthread_cancel()终止同一进程中的另一个线程。

3)线程可调用pthread_exit()终止自己。

    void pthread_exit(void *value_ptr);
 
 

无返回值,总是成功。

注:pthread_exit或者return返回的指针所指向的内存单元必须是全局的或者malloc分配的,不能在线程函数的栈上分配。

    int pthread_cancel(pthread_t thread);
 
 

成功返回0,失败返回非零错误号。

被终止的线程的响应取决于可终止状态和类型(cancelability state and type).

注:如果任意一个线程调用exit或_exit,则整个进程的所有线程都终止。

  • 获取终止状态
int pthread_join(pthread_t thread, void **retval);
 
 

等待线程终止,并获取线程退出状态。该线程必须是joinable。调用该函数的线程将挂起等待,直到id为thread的线程终止。

retval:

1)如果thread线程通过return返回,thread线程函数返回值。

2)pthread_cancel()异常终止,则retval所指向的单元存放常量PTHREAD_CANCELED(-1)。

3)自己调用pthread_exit()终止,retval存放pthread_exit参数。

  • 分离线程
#include<pthread.h>
int pthread_detach(pthread_t thread);
 
 

标记线程thread为分离状态。当一个分离状态的线程终止时,它的资源自动释放给系统,不需要其他线程join。

成功返回0,失败返回错误号。

注:让线程自己pthread_detach(线程函数内调用)不好,库函数不是原子的。

注:不能对一个已经处于detach状态的线程调用pthread_join.==>EINVAL.

注:不能对同一线程调用两次pthread_join或pthread_detach,或者一个线程已经调用pthread_detach就不能再调用pthread_join了。

注:线程创建时,都应该调用pthread_join()或pthread_detach(),以使系统资源释放。

示例:pthread_detach(pthread_self());

  • 获取线程id
pthread_t pthread_self(void);
 
 

函数总是成功,返回id。

  • 信号函数

线程信号用pthread_sigmask, pthread_kill。

线程读写用pread/pwrite.(文件偏移不改变)

你可能感兴趣的:(线程函数)