多线程情况下,往往需要使用互斥变量来实现线程间的同步,实现资源正确共享。

linux下使用如下变量和函数

//条件变量
pthread_cond_t
int pthread_cond_init (pthread_cond_t *c, const pthread_condattr_t *a)
int pthread_cond_wait (pthread_cond_t *c, pthread_mutex_t *m)
int pthread_cond_timedwait (pthread_cond_t *c,pthread_mutex_t *m, const struct timespec *t)
int pthread_cond_signal (pthread_cond_t *c)
int pthread_cond_destroy (pthread_cond_t *c) //互斥变量
pthread_mutex_t
int pthread_mutex_init (pthread_mutex_t *m, const pthread_mutexattr_t *a)
int pthread_mutex_lock(pthread_mutex_t *m)
int pthread_mutex_unlock(pthread_mutex_t *m)
int pthread_mutex_destroy (pthread_mutex_t *m)

利用条件变量和互斥变量来实现一个互斥队列

#include <pthread.h>
const int SIZE = 100;
const int NUM = 200;
class MyQueue{
public:
MyQueue():head(0),tail(0){
//变量初始化
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&notempty, NULL);
pthread_cond_init(&notfull, NULL);
}
void push(int i);
int pop();
~MyQueue(){
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&notempty);
pthread_cond_destroy(&notfull);
} private:
bool is_full() {
return (tail + 1) % SIZE == head;
}
bool is_empty() {
return tail == head;
} private:
int buf[SIZE];
int head;
int tail;
pthread_mutex_t mutex; //互斥使用锁
pthread_cond_t notempty; //非空条件变量
pthread_cond_t notfull; //队列不满条件变量 }; //尾部插入元素
void MyQueue::push(int i) {
pthread_mutex_lock(&mutex);
while (is_full()) {
cout << "queue is full, wait" << endl;
pthread_cond_wait(&notfull, &mutex);
}
buf[tail] = i;
tail = (tail + 1) % SIZE;
//通知等待notempty的线程,队列不空
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&notempty);
} //头部取元素
int MyQueue::pop() {
pthread_mutex_lock(&mutex);
while (is_empty()) {
cout << "queue is empty, wait" << endl;
pthread_cond_wait(&notempty, &mutex);
}
int i = buf[head];
head = (head + 1) % SIZE;
//通知等待notfull的线程,队列不满
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&notfull);
return i;
} void* producer(void* args) {
MyQueue* queue = (MyQueue*)args;
for (int i = 0; i < NUM; ++i) {
queue->push(i);
cout << "push:" << i << endl;
}
}
void* consumer(void* args) {
MyQueue* queue = (MyQueue*)args;
for (int i = 0; i < NUM; ++i) {
cout << "pop:" << queue->pop() << endl;
}
}
int main() {
MyQueue queue; pthread_t pro_thread;
pthread_t con_thread;
pthread_create(&pro_thread, NULL, producer, &queue);
pthread_create(&con_thread, NULL, consumer, &queue); pthread_join(pro_thread, NULL);
pthread_join(con_thread, NULL);
cout << "End" << endl;
}

Linux多线程系列-2-条件变量的使用(线程安全队列的实现)的更多相关文章

  1. linux多线程同步pthread_cond_XXX条件变量的理解

    在linux多线程编程中,线程的执行顺序是不可预知的,但是有时候由于某些需求,需要多个线程在启动时按照一定的顺序执行,虽然可以使用一些比较简陋的做法,例如:如果有3个线程 ABC,要求执行顺序是A-- ...

  2. Linux多线程编程的条件变量

    在stackoverflow上看到一关于多线程条件变量的问题,题主问道:什么时候会用到条件变量,mutex还不够吗?有个叫slowjelj的人做了很好的回答,我再看这个哥们其他话题的一些回答,感觉水平 ...

  3. Linux 多线程编程—使用条件变量实现循环打印

    编写一个程序,开启3个线程,这3个线程的ID分别为A.B.C,每个线程将自己的ID在屏幕上打印10遍,要求输出结果必须按ABC的顺序显示:如:ABCABC….依次递推. 使用条件变量来实现: #inc ...

  4. C++并发编程 条件变量 condition_variable,线程安全队列示例

    1. 背景 c++11中提供了对线程与条件变量的更好支持,对于写多线程程序方便了很多. 再看c++并发编程,记一下学习笔记. 2. c++11 提供的相关api 3.1 wait wait用于无条件等 ...

  5. Linux同步机制(二) - 条件变量,信号量,文件锁,栅栏

    1 条件变量 条件变量是一种同步机制,允许线程挂起,直到共享数据上的某些条件得到满足. 1.1 相关函数 #include <pthread.h>  pthread_cond_t cond ...

  6. Linux互斥锁、条件变量和信号量

    Linux互斥锁.条件变量和信号量  来自http://kongweile.iteye.com/blog/1155490 http://www.cnblogs.com/qingxia/archive/ ...

  7. linux 互斥锁和条件变量

    为什么有条件变量? 请参看一个线程等待某种事件发生 注意:本文是linux c版本的条件变量和互斥锁(mutex),不是C++的. mutex : mutual exclusion(相互排斥) 1,互 ...

  8. linux网络编程-posix条件变量(40)

    举一个列子来说明条件变量: 假设有两个线程同时访问全局变量n,初始化值是0, 一个线程进入临界区,进行互斥操作,线程当n大于0的时候才执行下面的操作,如果n不大于0,该线程就一直等待. 另外一个线程也 ...

  9. linux C++ 多线程使用pthread_cond 条件变量

    1. 背景 多线程中经常需要使用到锁(pthread_mutex_t)来完成多个线程之间的互斥操作. 但是互斥锁有一个明显到缺点: 只有两种状态,锁定和非锁定. 而条件变量则通过允许线程阻塞并等待另一 ...

随机推荐

  1. .net/C# HttpWebRequest传送与接收参数

    public string PostData(string url, string data)//url:要发送到网站的地址 data:传送需要的参数 { HttpWebRequest myReque ...

  2. IOS 问题集锦

    1._ UIWebview 拦截URL的时候:_NSCFString containsString:]: unrecognized selector sent to instance 的解决方案 NS ...

  3. 8421BCD码转换为十进制

    这个转换和随意的认知是不同的,要了解BCD码和二进制码的区别 #define BCD_TO_BIN(val) ((val)=((val)&15) + ((val)>>4)*10) ...

  4. WebView 上传文件 WebChromeClient之openFileChooser函数

    原链接:http://blog.saymagic.cn/2015/11/08/webview-upload.html?utm_source=tuicool&utm_medium=referra ...

  5. screenX、clientX、pageX的区别

    screenX:鼠标位置相对于用户屏幕水平偏移量,而screenY也就是垂直方向的,此时的参照点也就是原点是屏幕的左上角. clientX:跟screenX相比就是将参照点改成了浏览器内容区域的左上角 ...

  6. Fresco简单的使用—SimpleDraweeView

    本文出处:http://blog.csdn.net/u011164565/article/details/51330778 Fresco是一个第三方库,github官网地址:https://githu ...

  7. android 定义 程序 Scheme 接收特定URI开启Activity

    场景:通过浏览器打开URL或者扫描软件扫描URL来启动本地应用 <intent-filter> <category android:name="android.intent ...

  8. Sql Server插入数据并返回自增ID,@@IDENTITY,SCOPE_IDENTITY和IDENT_CURRENT的区别

    预备知识:SQLServer的IDENTITY关键字IDENTITY关键字代表的是一个函数,而不是identity属性.在access里边没有这个函数,所以在access不能用这个语句.语法:iden ...

  9. Evaluation Clustering methods

    There are many evaluation measures available like entropy, recall, precision, F-measure, silhouette ...

  10. Python 7 —— 扩展与嵌入

    Python 7 —— 扩展与嵌入 所谓扩展是指,在Python当中调用其他语言,由于Python的问题主要是效率,这里的扩展主要是指扩展C C++程序(重点) 所谓嵌入是指,在其他语言当中可以调用P ...