标签:style class blog code java http
| 锁状态\需要加的锁 | 读模式加锁 | 写模式加锁 |
| 读模式 | 允许 | 阻塞直到所有线程释放读锁 |
| 写模式 | 阻塞直到写锁被释放 | 阻塞直到写锁被释放 |
| 不加锁 | 允许 | 允许 |
#include <stdio.h>
#include <pthread.h>
/* 自定义的条件 */
struct msg {
struct msg *m_next;
char *data;
};
struct msg *workq; /* 定义一个消息队列 */
pthread_cond_t qready = PTHREAD_COND_INITIALIZER; /* 静态分配条件变量 */
pthread_mutex_t qlock = PTHREAD_MUTEX_INITIALIZER; /* 静态分配互斥量 */
void process_msg(void)
{
struct msg *mp;
while (1)
{
pthread_mutex_lock(&qlock);
while (workq == NULL)
{
/* 此函数把线程放到等待条件的线程列表上,然后对互斥量解锁
* 函数返回时,互斥量再次被锁住
*/
pthread_cond_wait(&qready, &qlock);
}
/* 从消息队列头取出一个消息 */
mp = workq;
workq = workq->m_next;
pthread_mutex_unlock(&qlock);
printf("%s\n", mp->data); /* 打印收到的消息 */
}
}
void enqueue_msg(struct msg *mp)
{
pthread_mutex_lock(&qlock);
mp->m_next = workq; /* 新消息放队列头部 */
workq = mp;
pthread_mutex_unlock(&qlock);
pthread_cond_signal(&qready); /* 唤醒等待该条件的某个线程 */
}
void *thr_fn1(void *arg)
{
process_msg();
}
void *thr_fn2(void *arg)
{
struct msg msg1, msg2, msg3;
msg1.data = "Hello world";
msg2.data = "I love you";
msg3.data = "This is a test!";
/* 将消息放入队列 */
enqueue_msg(&msg1);
enqueue_msg(&msg2);
enqueue_msg(&msg3);
}
int main(void)
{
pthread_t tid1, tid2;
pthread_create(&tid1, NULL, thr_fn1, NULL);
pthread_create(&tid2, NULL, thr_fn2, NULL);
pthread_join(tid1, NULL);
return 0;
}
Java逐行读取文件有多少种方法?,布布扣,bubuko.com
标签:style class blog code java http
原文地址:http://blog.csdn.net/sunling_sz/article/details/30476483