How to use mutex

≯℡__Kan透↙ 提交于 2019-12-20 07:51:15

问题


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.



来源:https://stackoverflow.com/questions/23845653/how-to-use-mutex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!