Linux多線程函數pthread_create()函數

來源:互聯網
上載者:User

函數原型:

#include <pthread.h>

int pthread_create(pthread_t *thread, const pthread_attr_t *attr,void *(*start_routine) (void *), void *arg); 4個參數:

第一個參數:指向線程標示符pthread_t的指標;

第二個參數:設定線程的屬性

第三個參數:線程運行函數的起始地址

第四個參數:運行函數的參數
pthreadTest.c

通過pthread_self()擷取當前線程的ID

#include<stdio.h>#include<pthread.h>void *print_pthread_id(void *arg){        printf("current thread id is %u\n",(unsigned)pthread_self());}int main(int argc, char * argv[]){        pthread_t thread;        pthread_create(&thread,NULL,print_pthread_id,NULL);        sleep(1);        printf("main thread id is %u\n",(unsigned)pthread_self());        return 0;}
編譯時間必須加-lpthread,

運行結果:

current thread id is 2279393024main thread id is 2287691520

pthreadTest1.c

#include<stdio.h>#include<pthread.h>#include<stdlib.h>#include<unistd.h>#include<string.h>pthread_t t_id;void printf_tid_pid(const char *s){        pid_t pid;        pthread_t tid;        pid = getpid();        tid = pthread_self();        printf("%s pid %u tid %u (0x%x)\n",s,(unsigned)pid,(unsigned)tid,(unsigned)tid);}void *thread_fuction(void *arg){        printf_tid_pid("new thread: ");        return ((void*)0);}int main(int argc,int argv){        int err;        err = pthread_create(&t_id,NULL,thread_fuction,NULL);        if(err != 0 )        {                printf("create thread fail: %s\n",strerror(err));        }        printf_tid_pid("main thread");        sleep(1);        return 0;}

 gcc -o pthreadTest1 pthreadTest1.c -lpthread

 ./pthreadTest1
main thread pid 10437 tid 3091662592 (0xb8470700)
new thread:  pid 10437 tid 3083364096 (0xb7c86700)







聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.