1.定时器alarm()和setitimer()都不能用于限制子线程的指向时间,因为信号会被主线程捕获(参考第6章笔记)
2.思想
1.在子线程work中再创建一个子线程work2
2.work中注册一个信号SIG
3.将work线程的线程ID pid1作为参数传递给子线程work2
3.在work2中sleep(A)后, 调用pthread_kill(pid1, SIG);向子线程发送信号
4.当线程work收到work1发来的信号后,从信号函数中回收work2并退出work
3.示例代码及执行结果:
#include <stdio.h>
#include <stdbool.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <errno.h>
#include "list.h"
#include <sys/time.h>
#include <signal.h>
#include <pthread.h>
static pthread_t pid2;
void usr(int sig)
{
printf("usr, pid = %lu\n", pthread_self());
pthread_join(pid2, NULL);
pthread_exit(NULL);
}
void *work2(void *arg)
{
pthread_t pid1 = *(pthread_t *)arg;
sleep(3);
printf("work2, pid = %lu\n", pthread_self());
pthread_kill(pid1, SIGUSR1);
pthread_exit(NULL);
}
void *work1(void *arg)
{
pthread_t pid1 = pthread_self();
printf("work1, pid = %lu\n", pid1);
pthread_create(&pid2, NULL, work2, &pid1);
signal(SIGUSR1, usr);
while(1)
{
printf("work1\n");
sleep(1);
}
pthread_exit(NULL);
}
int main(int argc, char **argv)
{
pthread_t pid1;
printf("main pid = %lu\n", pthread_self());
pthread_create(&pid1, NULL, work1, NULL);
pthread_join(pid1, NULL);
return 0;
}
/* 执行结果:
book@gui_hua_shu:~/test/pool$ ./a.out
main pid = 139843064096512
work1, pid = 139843055785728
work1
work1
work1
work2, pid = 139843047393024
usr, pid = 139843055785728
book@gui_hua_shu:~/test/pool$
*/