gpt4 book ai didi

c - 使用线程编程 : output is changing after a series of runs

转载 作者:行者123 更新时间:2023-11-30 14:50:54 26 4
gpt4 key购买 nike

#include<stdio.h>
#include<pthread.h>
#include<unistd.h>
#include<signal.h>
void sig(int signo)
{
if(signo==SIGUSR1)
printf("hiiii\n");
}
void * runner(void * param)
{
signal(SIGUSR1,sig);
while(1)
sleep(1);
}
int main()
{
pthread_t rid,sid;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_create(&sid,&attr,runner,NULL);
pthread_create(&rid,&attr,runner,NULL);
//sleep(1);
pthread_kill(sid,SIGUSR1);
printf("hey\n");
pthread_kill(rid,SIGUSR1);
pthread_join(rid,NULL);
}

输出:

harikrishna@harikrishna:~/Desktop/Ass3b_43$ ./a.out
User defined signal 1
harikrishna@harikrishna:~/Desktop/Ass3b_43$ ./a.out
User defined signal 1
harikrishna@harikrishna:~/Desktop/Ass3b_43$ ./a.out
User defined signal 1
harikrishna@harikrishna:~/Desktop/Ass3b_43$ ./a.out
User defined signal 1
harikrishna@harikrishna:~/Desktop/Ass3b_43$ ./a.out
User defined signal 1
harikrishna@harikrishna:~/Desktop/Ass3b_43$ ./a.out
User defined signal 1
harikrishna@harikrishna:~/Desktop/Ass3b_43$ ./a.out
User defined signal 1
harikrishna@harikrishna:~/Desktop/Ass3b_43$ ./a.out
hey
hiiii
hiiii
^C
harikrishna@harikrishna:~/Desktop/Ass3b_43$

最佳答案

您遇到的问题是您从线程注册信号处理程序。由于线程不同步,因此可以在注册处理程序之前将信号发送到线程。

当您看到“用户定义的信号 1”时,这意味着您在注册信号处理程序之前将信号发送到线程。

由于信号处理程序在线程之间共享,因此您不必从线程中注册它:您可以在创建线程之前进行注册:

#include<stdio.h>
#include<pthread.h>
#include<unistd.h>
#include<signal.h>

void sig(int signo)
{
if(signo==SIGUSR1)
printf("hiiii\n");
}

void * runner(void * param)
{
while(1)
sleep(1);
}

int main()
{
pthread_t rid,sid;
pthread_attr_t attr;

/* register signal handler */
signal(SIGUSR1,sig);

/* create thread */
pthread_attr_init(&attr);
pthread_create(&sid,&attr,runner,NULL);
pthread_create(&rid,&attr,runner,NULL);

/* send signals */
pthread_kill(sid,SIGUSR1);
printf("hey\n");
pthread_kill(rid,SIGUSR1);

/*terminate thread*/
pthread_cancel(sid);
pthread_cancel(rid);

/* join */
pthread_join(sid,NULL);
pthread_join(rid,NULL);
}

使用此代码,您仍然可以混合使用 hiiihey,但您不应再拥有用户定义的信号 1

关于c - 使用线程编程 : output is changing after a series of runs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48680654/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com