限制指定子线程work执行时间为A秒

    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$
*/

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值