- #include <stdio.h>
- #include <unistd.h>
- #include <stdlib.h>
- #include <string.h>
- #include <pthread.h>
- char message[]="hello world ";
- void *thread_function(void *arg)//線程函數
- {
- printf("thread_function is running, Argument is %s\n",(char *)arg);
- sleep(3);
- strcpy(message,"Bye!");
- pthread_exit("Thank you for the cpu time");//www.linuxidc.com注意線程退出函數
- }
-
- int main()
- {
- int res;
- pthread_t a_thread; //新線程的標識符
- void *thread_result;//定義一個線程返回值
- res=pthread_create(&a_thread,NULL,thread_function,(void *)message);//創建線程
- if(res!=0)//線程創建不成功
- {
- perror("Thread create error!");
- exit(EXIT_FAILURE);
- }
- printf("waiting for thread to finish...\n");
- res=pthread_join(a_thread,&thread_result);//等待新線程結束
- if(res!=0)
- {
- perror("Thread join error!");
- exit(EXIT_FAILURE);
- }
- printf("Thread joined , it returned %s\n",(char *)thread_result);
- printf("Message is now %s\n",message);
- exit(EXIT_SUCCESS);
- }
注意,多線程的編譯和普通程序的編譯是不一樣的,要用這樣的命令: 【cc -D_REENTRANT thread.c -g -o thread -lpthread】
大家可以看到,全局變量message經過線程創建函數傳遞給線程函數後由【hello world】變成了【Bye!】
- res=pthread_join(a_thread,&thread_result);//等待新線程結束
等待新線程結束,只有新線程結束後才會向下執行。