C语言编程中借助pthreads库进行多线程编程的示例

2020-01-06 14:05:01丽君

这样的形式,完全是为了迎合pthread_create函数的参数类型,你也可以不这样定义,只要在调用pthread_create创建线程的时候强制转换一下指针类型就可以了。

这两个函数将被用做线程的执行体,也就是说在两个线程里同时运行这两个函数。

现在我们来看main函数,和pthread有关的调用都在这里了。

pthread_t是线程结构,用来保存线程相关数据,你也可以理解为是线程类型,声明一个线程对象(变量)。

 

 
  1. pthread_t t1;  pthread_t t2; 

这里我们声明了两个线程变量t1,t2

 

 
  1. pthread_create(&t1,NULL,tprocess1,NULL);  pthread_create(&t2,NULL,tprocess2,NULL); 

这两句非常重要,pthread_create用来创建线程并启动,他的原型是

 

 
  1. int pthread_create(pthread_t * thread, pthread_attr_t * attr, void * (*start_routine)(void *), void * arg);