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。
舉例:
- /*thread.c*/
- #include <stdio.h>
- #include <pthread.h>
- /*線程一*/
- void thread_1(void)
- {
- int i=0;
- for(i=0;i<=6;i++)
- {
- printf("This is a pthread_1.\n");
- if(i==2)
- pthread_exit(0);
- sleep(1);
- }
- }
- /*線程二*/
- void thread_2(void)
- {
- int i;
- for(i=0;i<3;i++)
- printf("This is a pthread_2.\n");
- pthread_exit(0);
- }
- int main(void)
- {
- pthread_t id_1,id_2;
- int i,ret;
- /*創建線程一*/
- ret=pthread_create(&id_1,NULL,(void *) thread_1,NULL);
- if(ret!=0)
- {
- printf("Create pthread error!\n");
- return -1;
- }
- /*創建線程二*/
- ret=pthread_create(&id_2,NULL,(void *) thread_2,NULL);
- if(ret!=0)
- {
- printf("Create pthread error!\n");
- return -1;
- }
- /*等待線程結束*/
- pthread_join(id_1,NULL);
- pthread_join(id_2,NULL);
- return 0;
- }
以下是程序運行結果:
備註:pthread庫不是Linux系統默認的庫,連接時需要使用靜態庫libpthread.a,所以在線程函數在編譯時,需要連接庫函數,如上圖 gcc pthread_create.c -o pthread_create -lpthread