首页 > 解决方案 > 为什么信号量不阻塞第二个线程?(C)

问题描述

我想编写一个简单的 C 程序来更好地理解信号量。有两个线程,它们都调用相同的函数。第一个,增加全局变量,第二个线程,减少全局变量。

我试图在第一个线程完成工作之前阻止第二个线程使用该函数。但我仍然得到错误的答案:-2000。看起来两个线程都有偏移量-1。我该如何解决这个问题,使输出始终为 0?我认为函数内部的 sem_wait 应该阻塞第二个线程,直到第一个线程结束。因此偏移量应该保持为 1。

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

#define NUM_LOOPS 1000
long long counter = 0;
sem_t sem;
sem_t sem1;
void* counting_thread(void* arg) {
    sem_wait(&sem);
    int offset = *(int*) arg;
    int i;
    for(i = 0; i < NUM_LOOPS; i++){
        //sem_wait(&sem);
        counter += offset;
        printf("offset = %d\n", offset1);


        //sem_post(&sem);
    }
    sem_post(&sem);

    pthread_exit(NULL);
}

int main() {
    sem_init(&sem, 0, 1);

    pthread_t th1;
    int offset = 1;
    pthread_create(&th1, NULL, &counting_thread, &offset);
    //sem_post(&sem1);

    pthread_t th2;
    offset = -1;
    pthread_create(&th2, NULL, &counting_thread, &offset);

    pthread_join(th1, NULL);
    pthread_join(th2, NULL);

    printf("Finnal counter value: %lld\n", counter);
    sem_destroy(&sem);
    return 0;
}

标签: cmultithreadingoperating-systempthreadssemaphore

解决方案


根据pthread_create 手册页

注释 有关 pthread_create() 在 *thread 中返回的线程 ID 的更多信息,请参见 pthread_self(3)。除非采用实时调度策略,否则在调用 pthread_create() 之后, 不确定哪个线程(调用者或新线程)接下来将执行。

不能保证谁将执行下一个。也许对您来说,main线程正在执行下一个并offset to -1在新线程之前进行设置,使其能够从中读取更新的值offsetis -1


您可以使用条件变量进行同步。

例如 :

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

#define NUM_LOOPS 1000
long long counter = 0;
sem_t sem;
sem_t sem1;
pthread_cond_t cond1 = PTHREAD_COND_INITIALIZER; 
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; 


void* counting_thread(void* arg) {
    sem_wait(&sem);
    int offset = *(int*) arg;
    pthread_cond_signal(&cond1); 

    int i;
    for(i = 0; i < NUM_LOOPS; i++){
      counter += offset;
        printf("offset = %d\n", offset);

  }
    sem_post(&sem);

    pthread_exit(NULL);
}

int main() {
    sem_init(&sem, 0, 1); 

    int offset = 1;
    pthread_t th1;
    pthread_create(&th1, NULL, &counting_thread, &offset);


    pthread_cond_wait(&cond1, &lock);
    pthread_t th2;
    offset = -1;
    pthread_create(&th2, NULL, &counting_thread, &offset);

    pthread_join(th1, NULL);
    pthread_join(th2, NULL);

    printf("Finnal counter value: %lld\n", counter);
    sem_destroy(&sem);
    return 0;
}

推荐阅读