歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Linux下線程的創建和等待

Linux下線程的創建和等待

日期:2017/3/1 11:08:43   编辑:Linux編程
  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. #include <pthread.h>
  6. char message[]="hello world ";
  7. void *thread_function(void *arg)//線程函數
  8. {
  9. printf("thread_function is running, Argument is %s\n",(char *)arg);
  10. sleep(3);
  11. strcpy(message,"Bye!");
  12. pthread_exit("Thank you for the cpu time");//www.linuxidc.com注意線程退出函數
  13. }
  14. int main()
  15. {
  16. int res;
  17. pthread_t a_thread; //新線程的標識符
  18. void *thread_result;//定義一個線程返回值
  19. res=pthread_create(&a_thread,NULL,thread_function,(void *)message);//創建線程
  20. if(res!=0)//線程創建不成功
  21. {
  22. perror("Thread create error!");
  23. exit(EXIT_FAILURE);
  24. }
  25. printf("waiting for thread to finish...\n");
  26. res=pthread_join(a_thread,&thread_result);//等待新線程結束
  27. if(res!=0)
  28. {
  29. perror("Thread join error!");
  30. exit(EXIT_FAILURE);
  31. }
  32. printf("Thread joined , it returned %s\n",(char *)thread_result);
  33. printf("Message is now %s\n",message);
  34. exit(EXIT_SUCCESS);
  35. }

注意,多線程的編譯和普通程序的編譯是不一樣的,要用這樣的命令: 【cc -D_REENTRANT thread.c -g -o thread -lpthread】

大家可以看到,全局變量message經過線程創建函數傳遞給線程函數後由【hello world】變成了【Bye!】

  1. res=pthread_join(a_thread,&thread_result);//等待新線程結束
等待新線程結束,只有新線程結束後才會向下執行。
Copyright © Linux教程網 All Rights Reserved