多线程和实现线程安全入队操作

时间:2019-11-27 07:23:03

标签: c multithreading queue pthreads semaphore

我有一个使用信号量实现的队列,以使其成为线程安全的。基本上,它不允许多个线程同时进入队列。这是入队功能:

int queueEnqueue(queue* q, int* value){
    int value1;
    sem_getvalue(&(q->sem1),&value1);
    //printf("Value of semaphore is: %d\n", value1); 
    sem_wait(&(q->sem1));
    if(!queueIsFull(q)){
        q->rear = (q->rear + 1) % q->capacity;
        q->array[q->rear] = *value;
        q->size = q->size + 1;
        sem_post(&(q->sem1));
        return(1);
    }
    sem_post(&(q->sem1));
    return(0);
}

我的主体中有这段代码,但是由于某种原因,我总是会返回错误11,这意味着“线程没有足够的资源”。 num_threads是10000,而我的ulimit -u是128。这是问题吗?有人告诉我我的程序应该仍然可以工作。

    for(j = 0; j < 10; j++){ // run the test 10 times
        printf("\n-------Run %d-------\n", j);
        printf("====Enqueuing...");
        for(i = 0; i < num_pthreads; i++) {
            //printf("%d\n", i);
            if ((rc = pthread_create(&threads[i], NULL, enqueueThread, (void*) q))) {
                fprintf(stderr, "error: pthread_create, rc1: %d\n", rc);
                return EXIT_FAILURE;
            } 
        } 

我刚刚使用num_threads 10进行了测试,它可以正常工作,但是100左右的任何值都会引发错误。

0 个答案:

没有答案