Nivas B
Nivas B

Reputation: 25

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

Output1 :

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$

output2:

MAIN LOOP

 MAIN LOOP

 MAIN LOOP

 Send Thread
 Send Thread
 Send Thread
 Send Thread
 Send Thread
 MAIN LOOP
 Error creating thread=379

In the above code. the code should run infinitely when I press 's' or 'r' it should print "send thread" or "receive thread" accordingly for infinite number of times whereas in this code approx 380 times only the while loop is running.I don't know why it is happening.I have used variable count for debugging purpose,can anyone help?

Upvotes: 0

Views: 727

Answers (1)

David Schwartz
David Schwartz

Reputation: 182763

You need to either detach your threads or join them. Otherwise, you will run out of resources.

Upvotes: 1

Related Questions