多线程一个错误的例子

见源码:


/*********    说明:
*********    1.要让读者与写者之间、以及写者与写者之问要互斥地访同数据集;
*********    2.在无写进程到来时各读者可同时访问数据集;
*********    3.在读者和写者都等待时访问时写者优先.
*********/

#include <pthread.h>
#include <signal.h>
#include <stdio.h>
//#include "apue.h"

#define R 5 // reader NO.
#define W 5 // reader and writer NO.

pthread_mutex_t critical = PTHREAD_MUTEX_INITIALIZER; //保护临界资源互斥
pthread_mutex_t rd = PTHREAD_MUTEX_INITIALIZER; //保护读互斥
pthread_mutex_t wr = PTHREAD_MUTEX_INITIALIZER; //保护写互斥
pthread_mutex_t priority = PTHREAD_MUTEX_INITIALIZER;//读写互斥

int readCount = 0; //临界资源
int writeCount = 0; //临界资源

void* reader(void *arg)
{
    int n = W;
    int id = *(int *)arg;
    while (1)
    {
         sleep(rand()%3);
         readCount++; //对于临街资源必须做到互斥访问,同一时间只有一个线程在操作.
         if(readCount == 1){
             printf("AAAAAAAAA\n");
             pthread_mutex_lock(&critical);
         }
         readCount--;
         sleep(rand()%3);
         if(readCount == 0){
             printf("BBBBBBB\n");
             pthread_mutex_unlock(&critical);
         }
    }
    printf("-----reader %d has done ----, current read count[%d]\n", id, readCount);
}

void *writer(void *arg)
{
     int n = W;
     while(1)
     {
         sleep(rand()%3);
         pthread_mutex_lock(&wr);
         pthread_mutex_lock(&critical); //写线程之间也是互斥的.
         printf("\twriter is writing\n");
         pthread_mutex_unlock(&critical);
         pthread_mutex_unlock(&wr);
     }
     printf("-----writer has done -----\n");
}

int main(int argc, const char *argv[])
{
     int err;
     pthread_t tid[R], writerTid;
     int i= 0;
     //for(i; i < W; ++i){
         err = pthread_create(&tid[i], NULL, reader, &i);
         if (err != 0)
         {
             printf("can't create process for reader");
         }
     //}

     err = pthread_create(&writerTid, NULL, writer, (void *)NULL);
     if (err != 0)
     {
          printf("can't create process for writer");
     }

     while(1);
     return 0;
}

编译运行:

AAAAAAAAA
    writer is writing
BBBBBBB
AAAAAAAAA
BBBBBBB
    writer is writing
    writer is writing
    writer is writing
AAAAAAAAA
    writer is writing
BBBBBBB
    writer is writing
    writer is writing
AAAAAAAAA
BBBBBBB
AAAAAAAAA
    writer is writing
BBBBBBB
    writer is writing
AAAAAAAAA
BBBBBBB
AAAAAAAAA
    writer is writing
BBBBBBB
    writer is writing
AAAAAAAAA
BBBBBBB

见上面的红色部分,之前一直以为write一定会执行在BBBB后面,因为打印完"BBBBBB"后才会释放锁.

但是这些writing 的输出其实是在"AAAAA"打印完成之后和获取锁之前执行的,write线程里面的代码和read线程代码并没有先后顺序的关系.加上锁只能让他们访问资源时互斥,并不能做到同步.

 

posted @ 2015-07-08 18:03  Magnum Programm Life  阅读(288)  评论(0编辑  收藏  举报