简体   繁体   English

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

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

I am currently going over an example our professor gave us before our current assignment with semaphores and pthreading in C++. 我目前正在研究一个示例,在我们当前的作业之前,我们的教授在C ++中使用了信号量和pthreading。 Currently, the entire program waits when one of the threads is blocked. 当前,当线程之一被阻塞时,整个程序将等待。

#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);
}

The program should run the 'work' thread continuously until enough is in the account (1000), then it will buy an iPhone. 该程序应连续运行“工作”线程,直到帐户中有足够的数量(1000),然后才能购买iPhone。 My code will run until it hits the sem_wait(s2) semaphore in the 'buy' thread, which blocks the thread as it should, but my entire program waits and does not run the 'work' thread again. 我的代码将一直运行,直到它到达“购买”线程中的sem_wait(s2)信号量为止,该信号将按应有的方式阻塞该线程,但是我的整个程序会等待并且不再运行“工作”线程。

You're calling pthread_exit(NULL); 您正在调用pthread_exit(NULL); on every iteration through your loop in work . work循环中的每次迭代中。 Basically it's acting like there's no loop. 基本上,它的行为就像没有循环。

Maybe you mean something more like: 也许您的意思更像是:

  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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM