Problem with simple pthread program in C

Joined
Mar 9, 2023
Messages
1
Reaction score
0
So I just started programming for fun and looked into pthread since the topic interests me.

To understand the basics I tried to create a simple program that creates 2 threads and executes a function in each of them.

C:
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>

void *function1(void *printf);
void *function2(void *printf);

int main()
{
    pthread_t thread1;
    pthread_t thread2;

    pthread_create(&thread1, NULL, function1, NULL);
    function1(printf);
    pthread_join(thread1, NULL);

    pthread_create(&thread2, NULL, function2, NULL);
    function2(printf);
    pthread_join(thread2, NULL);

    return 0;
}

void *function1(void *print)
{
    printf("Thread1\n");

    return NULL;
}

void *function2(void *print)
{
    printf("Thread2\n");

    return NULL;
}

The Output should be:
Thread1
Thread2

instead I get:
Thread1
Thread1
Thread2
Thread2

Why does it execute the function twice?

Thanks for your time :)
 
Joined
Mar 5, 2023
Messages
8
Reaction score
3
The reason why the function is executed twice is that you are calling it twice, once with `pthread_create` and once directly. When you call the function with `pthread_create`, it creates a new thread and executes the function in that thread. However, when you call the function directly, it executes in the current thread.

To fix this, you should remove the direct function calls and only use `pthread_create` to create the threads and execute the functions in them. Here's the modified code:

Code:
#include <stdio.h>
#include <pthread.h>

void *function1(void *print);
void *function2(void *print);

int main()
{
    pthread_t thread1, thread2;

    pthread_create(&thread1, NULL, function1, NULL);
    pthread_create(&thread2, NULL, function2, NULL);

    pthread_join(thread1, NULL);
    pthread_join(thread2, NULL);

    return 0;
}

void *function1(void *print)
{
    printf("Thread1\n");
    return NULL;
}

void *function2(void *print)
{
    printf("Thread2\n");
    return NULL;
}
Hope this helps!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,534
Members
45,008
Latest member
Rahul737

Latest Threads

Top