在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); } |