总感觉Java线程这块缺了些啥,看源代码有时候看不太懂。因此就萌生了我下面的想法,学习pthread的相关知识,去探究Java Thread对象的底层是如何实现。基于这样的缘由我在某位大佬的基础写了下面的代码。
之前没有写过pthrea的代码,这里主要是做个记录,通过生产者和消费者模式这个例子来了解pthread的简单用法。
1、简单工具类:
template<typename T>class MyToolsQueue {private:queue<T> myQueeu;pthread_mutex_t mutex;pthread_cond_t cond;public:MyToolsQueue() {pthread_mutex_init(&mutex, 0);pthread_cond_init(&cond, 0);}~MyToolsQueue() {pthread_mutex_destroy(&mutex);pthread_cond_destroy(&cond);}void add(T t) {pthread_mutex_lock(&mutex);myQueeu.push(t);pthread_cond_broadcast(&cond);pthread_mutex_unlock(&mutex);}void get(T &t) {pthread_mutex_lock(&mutex);while (myQueeu.empty()) {cout<<"等待中 ... "<<endl;pthread_cond_wait(&cond, &mutex);}t = myQueeu.front();myQueeu.pop();pthread_mutex_unlock(&mutex);}};
2、调用工具类的代码
MyToolsQueue<int> myToolsQueue;void *getTask(void *pVoid) {cout << "getTask()" << endl;int result;while(true){myToolsQueue.get(result);cout<<"result = "<<result<<endl;if(result == -1){break;}}return 0;
}void *setTask(void *pVoid) {cout << "setTask()" << endl;int input;while (true){cin >> input;if(input == -1){myToolsQueue.add(input);break;}myToolsQueue.add(input);}return 0;
}int main() {cout << "pthread And queue" << endl;pthread_t pthread_get;pthread_t pthread_set;pthread_create(&pthread_get, nullptr, getTask, nullptr);pthread_create(&pthread_set, nullptr,setTask, nullptr);pthread_join(pthread_get,0);pthread_join(pthread_set,0);return 0;
}
3、效果: