转: pthread_create()

时间:2023-03-09 08:50:59
转: pthread_create()

pthread_create函数

原型:int  pthread_create((pthread_t  *thread,  pthread_attr_t  *attr,  void  *(*start_routine)(void  *),  void  *arg)

用法:#include  <pthread.h>

功能:创建线程(实际上就是确定调用该线程函数的入口点),在线程创建以后,就开始运行相关的线程函数。

说明:thread:线程标识符;

attr:线程属性设置;

start_routine:线程函数的起始地址;

arg:传递给start_routine的参数;

返回值:成功,返回0;出错,返回-1。

举例:

  1. /*thread.c*/
  2. #include <stdio.h>
  3. #include <pthread.h>
  4. /*线程一*/
  5. void thread_1(void)
  6. {
  7. int i=0;
  8. for(i=0;i<=6;i++)
  9. {
  10. printf("This is a pthread_1.\n");
  11. if(i==2)
  12. pthread_exit(0);
  13. sleep(1);
  14. }
  15. }
  16. /*线程二*/
  17. void thread_2(void)
  18. {
  19. int i;
  20. for(i=0;i<3;i++)
  21. printf("This is a pthread_2.\n");
  22. pthread_exit(0);
  23. }
  24. int main(void)
  25. {
  26. pthread_t id_1,id_2;
  27. int i,ret;
  28. /*创建线程一*/
  29. ret=pthread_create(&id_1,NULL,(void  *) thread_1,NULL);
  30. if(ret!=0)
  31. {
  32. printf("Create pthread error!\n");
  33. return -1;
  34. }
  35. /*创建线程二*/
  36. ret=pthread_create(&id_2,NULL,(void  *) thread_2,NULL);
  37. if(ret!=0)
  38. {
  39. printf("Create pthread error!\n");
  40. return -1;
  41. }
  42. /*等待线程结束*/
  43. pthread_join(id_1,NULL);
  44. pthread_join(id_2,NULL);
  45. return 0;
  46. }

以下是程序运行结果:

转: pthread_create()

备注:pthread库不是Linux系统默认的库,连接时需要使用静态库libpthread.a,所以在线程函数在编译时,需要连接库函数,如上图    gcc pthread_create.c -o pthread_create -lpthread