一、線程的ID
pthread_t:結構體(FreeBSD5.2、Mac OS10.3)/unsigned long int(linux)
/usr/include/bits/pthreadtypes.h
擷取線程ID:pthread_self()
一個執行個體:擷取主線程ID
點選(此處)折疊或打開
#include "apue.h"
int main()
{
pid_t pid;
pthread_t tid;
pid = getpid();
tid = pthread_self();
printf("pid is %u, tid is %x\n", pid, tid);
return 0;
}
思考:線程ID出了程序範圍還有效嗎?
二、創造新線程
int pthread_create(pthread_t *restrict tidp,
const pthread_attr_t *restrict attr,
void *(*start_routine)(void *),
void *restrict arg)
第一個參數:新線程的id,如果成功則新線程的id回填充到tidp指向的記憶體
第二個參數:線程屬性(排程政策,繼承性,分離性...)
第三個參數:回調函數(新線程要執行的函數)
第四個參數:回調函數的參數
傳回值:成功傳回0,失敗則傳回錯誤碼
編譯時需要連接配接庫libpthread
執行個體:建立線程,列印ID
程式框圖
/*AUTHOR: WJ
*DATE: 2015-3-18
*
*getpid() 擷取程序ID
*pthread_self() 擷取ID
*int pthread_create(pthread_t *thread,
* const pthread_attr_t *attr,
* void *(*start_routine) (void *),
* void *arg);
*第一個參數,新線程id,建立成功系統回填
*第二個參數,新線程到屬性,NULL為預設屬性
*第三個參數,新線程到啟動函數
*第四個參數,傳遞給新線程
*/
void print_id(char *s)
printf("%s pid is %u, tid is 0x%x\n", s, pid, tid);
void *thread_fun(void *arg)
print_id(arg);
return (void *)0;
pthread_t ntid;
int err;
err = pthread_create(&ntid, NULL, thread_fun, "new thread");
if(err != 0 )
{
printf("create new thread failed\n");
return 0;
}
print_id("main thread :");
sleep(2);