1. 如何來標識一個線程?
表示進程號的為pid_t類型,表示線程號的是pthread_t類型。pthread_t是一個結構體而不是整型。
使用pthread_equal確定兩個線程號是否相等:
#include
int pthread_equal(pthread_t tid1, pthread_t tid2);
Returns: nonzero if equal, 0 otherwise
使用pthread_self函數來獲取線程的ID:
#include
pthread_t pthread_self(void);
Returns: the thread ID of the calling thread
2.如何創建一個新線程?
使用pthread_create函數創建一個新線程。
以下是代碼片段: #include int pthread_create(pthread_t *restrict tidp, const pthread_attr_t *restrict attr, void *(*start_rtn)(void), void *restrict arg); Returns: 0 if OK, error number on failure |
當該函數成功返回的時候,tidp所指向的內存位置將被分配給新創建的帶有thread ID的線程。
attr用來定制各種線程參數。
新創建的線程將在start_rtn函數所指向的地址開始運行,該函數接受一個參數無類型的指針arg作為參數
線程創建時無法保證哪個線程會先運行。新創建的線程可以訪問進程地址空間,并且繼承了調用線程的浮點環境以及信號量掩碼,但對于線程的未決信號量也將會被清除。
下面的這段程序創建新的線程,并打印線程id,新線程通過pthread_self函數獲取自己的線程ID。
#include "apue.h"
#include
pthread_t ntid;
void printids(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 int)pid,
(unsigned int)tid, (unsigned int)tid);
}
void * thr_fn(void *arg)
{
printids("new thread: ");
return((void *)0);
}
int main(void)
{
int err;
err = pthread_create(&ntid, NULL, thr_fn, NULL);
if (err != 0)
err_quit("can\'t create thread: %s\\n", strerror(err));
printids("main thread:");
sleep(1);
exit(0);
}
3. 如何實現單個線程的退出?
如果一個線程調用了exit, _Exit, 或者_exit,將導致整個進程的終止。要實現單個線程的退出,可以采用如下方式:
o 線程可以簡單的從start routine返回,返回值就是線程的退出代碼。
o 線程可以被同一進程中的其它線程終止。
o 線程調用pthread_exit
#include
void pthread_exit(void *rval_ptr);
4.如何使調用線程阻塞等待指定線程的退出,并獲得退出線程的返回碼?
#include
int pthread_join(pthread_t thread, void **rval_ptr);
Returns: 0 if OK, error number on failure
調用線程將會被阻塞直到指定的線程終止。如果線程簡單的從start routine返回則rval_ptr將包含返回代碼。如果線程是被撤銷(調用pthread_exit)的,rval_ptr指向的內存地址將被設置為PTHREAD_CANCELED.
通過調用pthread_join,我們自動的將一個線程變成分離狀態,這樣就可以實現資源的回收。如果線程已經處于分離狀態,調用pthread_join將會失敗,并返回EINVAL。
如果我們對于線程的返回值不感興趣,可以將rval_ptr設置成NULL。
一段有缺陷的代碼:
#include "apue.h"
#include
struct foo {
int a, b, c, d;
};
void
printfoo(const char *s, const struct foo *fp)
{
printf(s);
printf(" structure at 0x%x\\n", (unsigned)fp);
printf(" foo.a = %d\\n", fp->a);
printf(" foo.b = %d\\n", fp->b);
printf(" foo.c = %d\\n", fp->c);
printf(" foo.d = %d\\n", fp->d);
}
void *
thr_fn1(void *arg)
{
struct foo foo = {1, 2, 3, 4};
printfoo("thread 1:\\n", &foo);
pthread_exit((void *)&foo);
}
void *
thr_fn2(void *arg)
{
printf("thread 2: ID is %d\\n", pthread_self());
pthread_exit((void *)0);
}
int
main(void)
{
int err;
pthread_t tid1, tid2;
原文轉自:http://blogread.cn/it/article/3344