Smiley7
Smiley7

Reputation: 235

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

Upvotes: 3

Views: 3073

Answers (2)

Pranav Sanwal
Pranav Sanwal

Reputation: 31

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.

Upvotes: 3

kiran Biradar
kiran Biradar

Reputation: 12732

Undefined behavior can happen if the function is not thread safe. For example if it uses some global data, has some static variables inside or receives as a parameter pointer so some data the same for each thread.

So usage of static variables should be removed, usage of global and common data should be wrapped by some synchronization mechanism like Criticalsections.

Answering your question your getMsg function is thead safe.

Upvotes: 0

Related Questions