簡體   English   中英

pthread輸入線程和工作線程同步

[英]pthread input thread and worker thread synchronization

我有兩個pthread,其中一個是從cin讀取並將其放入隊列,另一個是工作線程,每隔2秒檢查一次QUEUE,並在其中包含某些內容時進行打印。

這是我的主要內容:

#include <string>
#include <queue>
#include <iostream>
#include <stdio.h>
#include "Thread.h"
#include "Mutex.h"

using namespace std;

queue<string> lineup;
Mutex lock;

class InputReader:public Thread{
    private:
        string buffer;
    protected:
        virtual void run(){
            while(true){
                cout << "Please Enter some Text:\n" ;
                getline(cin,buffer);
                lock.lock();
                lineup.push(buffer);
                lock.unlock();
            }
        }
    public:
        InputReader(){}
        ~InputReader(){}
};


class Request: public Thread{
    protected:
        virtual void run(){
            while(true){
                sleep(2);
                lock.lock();
                if ((int)(lineup.size())>0){
                    cout << "Sending Request: " << lineup.front() << endl;
                    lineup.pop();
                }
                else{
                    cout << "Nothing to send!" <<endl;
                }
                lock.unlock();

            }
        }
    public:
        Request(){}
        ~Request(){}
};

int main(){
    Request rq;InputReader iread; 
    iread.start();  rq.start();
    iread.join(); rq.join();

    return 0;
}

其中Thread.h和Thread.cpp是:

#ifndef __THREAD_H__
#define __THREAD_H__
#include <pthread.h>

class Thread
{
    private:
        pthread_t thread;
        static void * dispatch(void *);
    protected:
        virtual void run() = 0;
    public:
        virtual ~Thread();
        void start();
        void join();
};

#endif

//  THREAD.CPP
#include "Thread.h"

Thread::~Thread(){}

void * Thread::dispatch(void * ptr)
{
    if (!ptr) return 0;
    static_cast<Thread *>(ptr)->run();
    pthread_exit(ptr);
    return 0;
}

void Thread::start(){
    pthread_create(&thread, 0, Thread::dispatch, this);
}

void Thread::join()
{
    pthread_join(thread, 0);
}

Mutex.h和Mutex.cpp:

#ifndef __MUTEX_H__
#define __MUTEX_H__
#include <pthread.h>

class Mutex
{
private:
    pthread_mutex_t mutex;
public:
    Mutex();
    ~Mutex();
    void lock();
    void unlock();
    bool trylock();
};

#endif

// MUTEX.CPP -----------------------
#include "Mutex.h"
Mutex::Mutex(){
       pthread_mutex_init(&mutex, 0);
   }
   Mutex::~Mutex(){
      pthread_mutex_destroy(&mutex);
  }
  void Mutex::lock(){
      pthread_mutex_lock(&mutex);
  }
  void Mutex::unlock(){
      pthread_mutex_unlock(&mutex);
  }
  bool Mutex::trylock()  {
      return (pthread_mutex_trylock(&mutex) == 0);
  }

問題是一旦它在無限循環中等待iread線程中的stdin,rq線程就永遠不會啟動。 實際上,無論哪個.start()首先出現,都是那個被卡住的...有什么想法嗎?

原來,我需要使用-lpthread選項運行g ++ 有誰知道為什么默認情況下不啟用此功能?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM