Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling the same functions from multiple threads

I have written a program in C that will start 2 threads (UDP/TCP). Each thread will send packets.

I am sending packets every 5 seconds in both threads. Both threads will call the same functions as shown below:

No global variables are being modified, and only the parameters are being used inside the shared functions.

Since no shared variables are being updated, it is safe for both threads to call the same function? Would this result in any undefined behavior?

//create message
int getMsg(char * msg, int size)
{
    char strMsg[size];
    sprintf(strMsg, "%d", 10);
    strcat(msg, strMsg);

    return EXIT_SUCCESS;        
}

// tcp
void send1()
{
    while(1)
    {
        // create message to send
        char str[100];
        int rVal;
        rVal = getMsg(str, 100);
        if(rVal != EXIT_FAILURE)
        {
            // send packet
            sendto(fd, strlen(str), 0, dest, sizeof(*dest));
        }
        usleep(5000000); 
    }
}

// udp
void send2()
{
    while(1)
    {
        // create message to send
        char msg[200];
        int rVal;
        rVal = getMsg(msg, 200);
        if(rVal != EXIT_FAILURE)
        {
            // send packet
            sendto(fd, strlen(str), 0, dest, sizeof(*dest));
        }
        usleep(5000000); 
    }
}
like image 490
Smiley7 Avatar asked Dec 17 '25 14:12

Smiley7


1 Answers

yes, it is safe to call common function through multiple threads as long as the function don’t incorporate use of global or static variables. each thread creates a seperate copy of called funtion onto their respective call stacks.

like image 116
Pranav Sanwal Avatar answered Dec 20 '25 08:12

Pranav Sanwal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!