pthread输入线程和工作线程同步

时间:2012-06-19 01:09:39

标签: c++ multithreading pthreads pthread-join

我有两个pthreads,其中一个是从cin读取并将其放入队列中,另一个是工作线程,每隔2秒检查一次队列,如果有内容则打印出来。

这就是我的主要内容:

#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()首先出现的是它被困在......任何想法?

1 个答案:

答案 0 :(得分:1)

原来我需要使用 -lpthread 选项运行 g ++ 。有谁知道为什么默认情况下没有开启?