[英]Infinite loop terminating in pthread
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <stdlib.h>
#include<signal.h>
#include<unistd.h>//getch();
#include <termios.h>//getch();
#include <pthread.h>
#include <unistd.h>
unsigned int sleep(unsigned int seconds);
volatile sig_atomic_t flag = 0;
int value = 0;
int count = 0;
char getch()
{
int buf = 0;
struct termios old = { 0 };
fflush(stdout);
if (tcgetattr(0, &old) < 0)
perror("tcsetattr()");
old.c_lflag &= ~ICANON;
old.c_lflag &= ~ECHO;
old.c_cc[VMIN] = 1;
old.c_cc[VTIME] = 0;
if (tcsetattr(0, TCSANOW, &old) < 0)
perror("tcsetattr ICANON");
if (read(0, &buf, 1) < 0)
perror("read()");
old.c_lflag |= ICANON;
old.c_lflag |= ECHO;
if (tcsetattr(0, TCSADRAIN, &old) < 0)
perror("tcsetattr ~ICANON");
return buf;
}
void *send_function(void *parg)
{
printf("\n Send Thread ");
count++;
return parg;
}
void *receive_function(void *parg)
{
printf("\n Receive Thread ");
count++;
return parg;
}
void my_function(int sig)
{
flag = 1; // set flag
}
int main()
{
char selection; //user input(s or r)
pthread_t send;
pthread_t receive;
while (1)
{
signal(SIGINT, my_function);
if (flag)
{
printf("\n Choose your terminal S or R \n");
selection = getch();
flag = 0;
}
if (selection == 's')
{
if (pthread_create(&send, NULL, send_function, NULL))
{
printf("Error creating thread=%d\n", count);
return 1;
}
}
else if (selection == 'r')
{
if (pthread_create(&receive, NULL, receive_function, NULL))
{
printf("Error creating thread=%d\n", count);
return 1;
}
}
printf("\n MAIN LOOP\n");
//sleep(1);
}
return 0;
//pthread_exit(NULL);
}
输出1:
MAIN LOOP
Receive Thread
MAIN LOOP
Receive Thread
MAIN LOOP
Receive Thread
MAIN LOOP
Receive Thread
Receive Thread
Receive Thread
Receive Thread Error creating thread=380
nivas@balakrishnan-HCL-Desktop:~/C_sample$
输出2:
MAIN LOOP
MAIN LOOP
MAIN LOOP
Send Thread
Send Thread
Send Thread
Send Thread
Send Thread
MAIN LOOP
Error creating thread=379
在上面的代码中。 当我按's'或'r'时,代码应无限运行,它应相应地打印“发送线程”或“接收线程”无限次,而在此代码中,大约380次仅运行while循环。我不知道为什么会这样。我已经将变量计数用于调试目的,有人可以帮忙吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.