|
|

楼主 |
发表于 2006-4-3 19:13:01
|
显示全部楼层
- ...
- void put(struct prodcons * b, int data)
- {
- pthread_mutex_lock(&b->lock);
-
- /* Wait until buffer is not full */
- while ((b->writepos + 1) % BUFFER_SIZE == b->readpos) {
- pthread_cond_wait(&b->notfull, &b->lock);
- /* pthread_cond_wait reacquired b->lock before returning */
- }
- /* Write the data and advance write pointer */
- b->buffer[b->writepos] = data;
- b->writepos++;
- if (b->writepos >= BUFFER_SIZE) b->writepos = 0;
- /* Signal that the buffer is now not full */
- pthread_cond_signal(&b->notempty);
- pthread_mutex_unlock(&b->lock);
- }
- ...
- void * producer(void * data)
- {
- ...
- for (n = 0; n < 5; n++) {
- printf("%d --->\n", n);
- put(&buffer, n);
-
- ...
- }
- #
- 0 --->
- 1 --->
- 2 --->
- 3 --->
- 4 --->
- ---> 0
- ---> 1
- ---> 2
- ---> 3
- ---> 4
复制代码
还有一个是consumer的subroutine,两者一存一取(实际上这些东西都可以在书上看到), 但我还有一个地方没弄明白。为什么输出是顺序的呢? 我这样理解的:
1. 在外层作5次循环时的第一次时,put先拿到了mutex----->再拿到condition-------->做一次数据的写,写完后---------〉释放condition--------〉 释放mutex
2. 这一刻前get一直在等待mutex, 这一刻开始应该是put和get同时去抢mutex,而显示时为什么总是put得到mutex呢? 做完5次循环后get才得到mutex?
Thanks in advance |
|