UNIX Pthreads&互斥;程序锁定

时间:2014-11-24 12:27:50

标签: c multithreading

以下情景:

我们应该使x线程最大化。我们的main函数应该创建一个带有指向函数' makeThreads'的新线程。此函数最多可以包含2个线程,具体取决于已存在的线程数。比赛条件是要避免的。 我被卡住了。我不确定如何解决我遇到的问题,部分原因是因为我无法自行识别问题。

建议非常感谢!

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

#define MAX_THR 20

pthread_mutex_t mutex;
int threadCount = 0;

int randomNbr(){
    int number = (rand() % 10) + 1;
    return number;
}

void *makeThreads(void* number){

    int rndnmb = *((int *) number);

    pthread_mutex_lock(&mutex);

    sleep(rndnmb);
    pthread_t threadDummy;
    int thread1, i, threadID, rndnbr;

    threadID = threadCount;
    printf("Hello from Thread %d!\n", threadID);

    for(i = 0; i < 2; i++){
        if(threadCount < MAX_THR){
            rndnbr = randomNbr();
            int *rnd = &rndnbr;
            threadCount++;
            thread1 = pthread_create(&threadDummy, NULL, *makeThreads, (void *) rnd);
            pthread_join(threadDummy, NULL);

        }
    }

    pthread_mutex_unlock(&mutex);
    printf("Goodbye from Thread %d!\n", threadID);
}

int main(){

    int t1, rndnbr;

    pthread_t threadOne;
    pthread_mutex_init(&mutex, NULL);

    srand(time(NULL));
    rndnbr = randomNbr();
    int *rnd = &rndnbr;
    threadCount++;
    t1 = pthread_create(&threadOne, NULL, *makeThreads, (void *) rnd);
    pthread_join(threadOne, NULL);

}

0 个答案:

没有答案