nzomkxia
nzomkxia

Reputation: 1267

multithreading(pthread) compete code

#include <unistd.h>
#include <pthread.h>
#include <stdio.h>
int global;
int i = 30; 
int j = 30; 
int k = 30; 
pthread_mutex_t mutex;
void* child1(void* arg)
{
    while(k--)
    {   
        pthread_mutex_lock(&mutex);
        global++;
        printf("from child1\n");
        printf("%d\n",global);
        pthread_mutex_unlock(&mutex);
    }   
}

void* child2(void* arg)
{
    while(j--)
    {   
        pthread_mutex_lock(&mutex);
        global++;
        printf("from child1\n");
        printf("%d\n",global);
        pthread_mutex_unlock(&mutex);
    }   
}

int main()
{

    pthread_t tid1, tid2;
    pthread_mutex_init(&mutex, NULL);
    pthread_create(&tid1, NULL, child1, NULL);
    pthread_create(&tid2, NULL, child2, NULL);   
    while(i--)
    {
        pthread_mutex_lock(&mutex);
        global++;
        printf("from main\n");
        printf("%d\n",global);
        pthread_mutex_unlock(&mutex);
    }
    return 0;
}

I'm new to pthread and multithreading, the result of this code is from main xx and child1 appeared rarely, the three threads never appear together, what's the problem?

Upvotes: 0

Views: 192

Answers (3)

psykoblast
psykoblast

Reputation: 116

I think you should use 3 differents mutex , by the way use pconditional control in order to avoid having unsafe access

Upvotes: 0

Venkat S A
Venkat S A

Reputation: 53

One suggestion in code replace printf("from child1\n"); to printf("from child2\n"); in void* child2(void* arg) function. And if you want ensure all threads to complete please add the following lines at end of main function. pthread_join(tid1,NULL); pthread_join(tid2,NULL);

Upvotes: 0

Brett Hale
Brett Hale

Reputation: 22318

Most of time in the critical sections will be spent in the printf calls. You might try:

{
    int local;

    pthread_mutex_lock(& mutex);
    local = ++global;
    pthread_mutex_unlock(& mutex);

    printf("from <fn>\n%d\n", local);
}

This still doesn't give any guarantee of 'fairness' however, but the printf call is very likely to use a system call or I/O event that will cause the scheduler to kick in.


Your program is similar to the Dining Philosophers Problem in many respects. You don't want any thread to 'starve', but you have contention between threads for the global counter, and you want to enforce an orderly execution.

Upvotes: 2

Related Questions