Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1016079
  • 博文数量: 162
  • 博客积分: 3887
  • 博客等级: 中校
  • 技术积分: 1617
  • 用 户 组: 普通用户
  • 注册时间: 2010-05-06 19:05
文章分类

全部博文(162)

文章存档

2015年(4)

2014年(7)

2013年(10)

2012年(16)

2011年(89)

2010年(36)

分类: C/C++

2013-06-08 15:59:51

原文地址:GThread多线程读写 作者:jcodeer

GThread创建类线程函数,第一类线程函数对全局变量进行写操作,另一类线程函数则对全局变量进行读操作。
#include
gint count = 0;


gpointer write_proc(gpointer data);
gpointer read_proc(gpointer data);

int main(int argc,char** argv){
    GThread* threads[50*2];
    int i = 0;

    g_thread_init(NULL);
    for(i = 0; i < 50;i++){
        threads[i] = g_thread_create(write_proc,NULL,TRUE,NULL);
    }

    for(i = 0; i < 50;i++){
        threads[i + 50] = g_thread_create(read_proc,NULL,TRUE,NULL);
    }


    for(i = 0; i < 50 * 2;i++)
        g_thread_join(threads[i]);

    g_print("After all threads exit count = %d\n",count);

    return 0;
}

gpointer write_proc(gpointer data){
    g_print("%08d:%s update count = %d\n",__LINE__,__FUNCTION__,count);
    count++;

    return NULL;
}

gpointer read_proc(gpointer data){
    g_print("%08d:%s read count = %d\n",__LINE__,__FUNCTION__,--count);
    
    return NULL;
}
下面的实例同样是两类线程函数,分别实现读操作和写操作,与上面的实例所不同的 是采用了线程参数。
#include
typedef struct WRData{
    gint count;
}WRData;

#define NUM 150
gpointer write_proc(gpointer data);
gpointer read_proc(gpointer data);

int main(int argc,char** argv){
    GThread* threads[NUM*2];
    int i = 0;
    WRData Count;

    Count.count = 0;
    g_thread_init(NULL);
    for(i = 0; i < NUM;i++){
        threads[i] = g_thread_create(write_proc,&Count,TRUE,NULL);
    }

    for(i = 0; i < NUM;i++){
        threads[i + NUM] = g_thread_create(read_proc,&Count,TRUE,NULL);
    }


    for(i = 0; i < NUM * 2;i++)
        g_thread_join(threads[i]);

    g_print("After all threads exit count = %d\n",Count.count);

    return 0;
}

gpointer write_proc(gpointer data){
    WRData* Count = (WRData*)data;
    g_print("%08d:%s update count = %d\n",__LINE__,__FUNCTION__,Count->count);
    Count->count++;

    return NULL;
}

gpointer read_proc(gpointer data){
    WRData* Count = (WRData*)data;
    g_print("%08d:%s read count = %d\n",__LINE__,__FUNCTION__,--Count->count);
    
    return NULL;
}

阅读(1869) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~