如何让一个 pthread 在另一个线程正在等待 C++ 中的信号量时继续?

How to have one pthread continue while another thread is waiting on a semaphore in C++?

我目前正在复习我们的教授在我们当前分配 C++ 中的信号量和 pthreading 之前给我们的一个例子。目前,当其中一个线程被阻塞时,整个程序都会等待。

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

using namespace std;

int account = 99;
bool sent = false;
int rate = 12;
int hours = 15;
sem_t s1;
sem_t s2;


//work thread
void *work(void*){
  while(1){
      sem_wait(&s1);
      account += hours * rate;
      cout << "Account: " << account << endl;
      if(account >= 1000 && !sent){
          sem_post(&s2);
          sent = true;
      }
      sem_post(&s1);

      pthread_exit(NULL);
  }
}

void* buy(void*){
  while(1){
      sem_wait(&s2);
      sem_wait(&s1);
      account -= 1000;
      sent = false;
      cout << "iPhone bought!! Account: " << account << endl;
      sem_post(&s1);
      pthread_exit(NULL);
  }
}

int main(){

  pthread_t workt, buyt;
    sem_init(&s1, 0, 1);
    sem_init(&s2, 0, 0);

  while(1){
    pthread_create( &workt, NULL, work, NULL);
    pthread_create( &buyt, NULL, buy, NULL);

    pthread_join(workt, NULL);
    pthread_join(buyt, NULL);
  }
    sem_close(&s1);
    sem_close(&s2);

    pthread_exit(NULL);
}

程序应该 运行 连续 'work' 线程直到帐户中有足够的 (1000),然后它会购买 iPhone。我的代码将 运行 直到它到达 'buy' 线程中的 sem_wait(s2) 信号量,这会按预期阻塞线程,但我的整个程序会等待并且不会 运行 'work' 线程再次。

您在 work 中的循环的每次迭代中调用 pthread_exit(NULL);。基本上它就像没有循环一样。

也许你的意思更像是:

  while(!sent){
      sem_wait(&s1);
      account += hours * rate;
      cout << "Account: " << account << endl;
      if(account >= 1000){
          sem_post(&s2);
          sent = true;
      }
      sem_post(&s1);

  }
  pthread_exit(NULL);