Pthread-限制一次可以访问函数的线程数

时间:2016-05-30 12:22:32

标签: c multithreading pthreads semaphore

我有一个简单的问题。我正在学习信号量,我只希望四个线程能够在任何给定时间访问someFunction()。此函数需要执行 num_task 次。这是我到目前为止所做的,但是valgrind正在抛出一些错误,说我有可能内存泄漏。请告诉我哪里出错了以及如何解决这个问题。谢谢!

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

sem_t s; 
typedef struct Data Data;
struct Data {
    int index;
    int j; 
};
void* someFunction(void* arg){ 
    // make sure only four threads access this function at once
    sem_wait(&s);
    Data* a = arg;
    printf("i%d j%d\n", a->index, a->j);
    sleep(1);  
    free(a); 
    sem_post(&s); 
    return 0;
}  
int main(void){
    int num_task = 10; // i need to call someFunction() 9000 times
    int num_threads = 4;
    sem_init(&s, 0, num_threads);
    int j = 0;
    pthread_t thread_ids[num_threads];
    for (int i = 0; i < num_task; i ++){ // these are our columns 
        sem_wait(&s);
        if (j > num_threads - 1){
            j = 0; // j goes 0 1 2 3 0 1 2 3 0 1 2 3 ....
        } 
        Data* a = malloc(sizeof(Data));
        a->index = i;
        a->j = j; 
        printf("MAIN j%d\n", j);
        pthread_create(thread_ids + j, NULL, someFunction, a); 
        j ++;
        sem_post(&s); 
    }
    for (int i = 0; i < num_threads; i ++){
        pthread_join(thread_ids[i], NULL);
    }
    sem_destroy(&s);
    return 0;
}

0 个答案:

没有答案