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;
}
阅读(3636) | 评论(0) | 转发(1) |