How to use mutex

2019-03-07 01:42发布

问题:

Where should i put the lock and unlock mutex in order for the threads to print alternatively? Thanks:D

Implement a program that creates two threads. The threads will print their ID (pthread_self) 10 times and then stop. Insure that the printed IDs alternate always (ie A, B, A, B, ...)

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

#define N 2
pthread_mutex_t mtx;
void* func (void* arg) {
    int i=0;
    int f=1;

    for(i=0; i<10; i++) {
        printf("%d%s%d\n",f ,":  ", (int)pthread_self());
        f++;
    }

    return NULL;
}

int main() {
    int i;
    pthread_t thr[N];
    pthread_mutex_init(&mtx, NULL);


    for(i=0; i<N; i++) {

        pthread_create(&thr[i], NULL, func, NULL);
    }

    for(i=0; i<N; i++) {
        pthread_join(thr[i], NULL);
    }
    pthread_mutex_destroy(&mtx);
    return 0;
}

回答1:

If you want the predictably ordered output A, B, A, B, A, B, the most appropriate tool to use is a single thread of control.

To do it wastefully with two threads, you can define a shared variable called "turn" which indicates whose turn it is to print something. Each thread waits on a condition variable until the "turn" variable is equal to itself. Then it carries out the sequential task, sets the "turn" variable to another thread and signals the condition.