在Linux中,默認情況下是在一個線程被創建後,必須使用此函數對創建的線程進行資源回收,但是可以設置Threads attributes來設置當一個線程結束時,直接回收此線程所佔用的系統資源,詳細資料查看Threads attributes。
2使用範例編輯
// 子線程阻塞,等待信號,然後輸出字符串
// 主線程從鍵盤錄入字符,給子線程發信號。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
|
#include<stdio.h> #include<unistd.h> #include<signal.h> #include<pthread.h> #include<time.h> pthread_ttid; sigset_tset; voidmyfunc() { printf ( "hello\n" ); } staticvoid*mythread( void *p) { intsignum; while (1){ sigwait(&set,&signum); if (SIGUSR1==signum) myfunc(); if (SIGUSR2==signum) { printf ( "Iwillsleep2secondandexit\n" ); sleep(2); break ; } } } intmain() { chartmp; void *status; sigemptyset(&set); sigaddset(&set,SIGUSR1); sigaddset(&set,SIGUSR2); sigprocmask(SIG_SETMASK,&set,NULL); pthread_create(&tid,NULL,mythread,NULL); while (1) { printf ( ":" ); scanf ( "%c" ,&tmp); if ( 'a' ==tmp) { pthread_kill(tid,SIGUSR1); //發送SIGUSR1,打印字符串。 } elseif( 'q' ==tmp) { //發出SIGUSR2信號,讓線程退出,如果發送SIGKILL,線程將直接退出。 pthread_kill(tid,SIGUSR2); //等待線程tid執行完畢,這裏阻塞。 pthread_join(tid,&status); printf ( "finish\n" ); break ; } else continue ; } return0; } |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
void *start_run( void *arg) { //dosomework } intmain() { pthread_tthread_id; pthread_attr_tattr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED); pthread_create(&thread_id,&attr,start_run,NULL); pthread_attr_destroy(&attr); sleep(5); exit (0); } |