分类: C/C++
2011-05-16 21:37:58
执行结果:
0
test 1
test 2
test 3
test 4
test 5
test 6
test 7
test 8
test 9
下面还有一个示例,向线程池中的线程传递一个结构体参数:
1 #include
2 #include
#include
3 #include
4
5 struct TEST {
6 int x;
7 int y;
8 };
9 static void test_function(gpointer data, gpointer user_data)
10 {
struct TEST test;
11 memcpy( &test, ( struct TEST * ) data, sizeof( struct TEST ) );
12 g_print("x:%d, y:%d\n", test.x, test.y );
13 }
14
15 int main()
16 {
17 GThreadPool *pool = NULL;
18 GError *error = NULL;
19
20 int i,gthreadcount;
21 GMutex *mutex;
22 if ( g_thread_supported () )
23 printf("support g_thread\n");
24 g_thread_init (NULL);
25 mutex = g_mutex_new();
26 pool = g_thread_pool_new(test_function,NULL,-1,FALSE,&error);
27 if(pool == NULL) {
28 g_print("can not create thread");
29 }
30
31 gthreadcount = g_thread_pool_get_num_threads(pool);
32 g_print("gthread count is %d\n",gthreadcount);
33
34 g_mutex_lock(mutex);
35 for(i = 1; i < 10 ; i++)
36 {
37 struct TEST test;
38 test.x = 0;
39 test.y = i;
40 g_thread_pool_push(pool, ( gpointer ) &test , &error);
41 usleep( 50000 );
42 if ( error != NULL )
43 {
44 g_print( "error:%s\n", error->message );
45 }
46 }
47 g_mutex_unlock(mutex);
48 g_thread_pool_free( pool, FALSE, TRUE );
49 return 0;
50 }
~
~
:sh
$ gcc -lglib-2.0 -lgthread-2.0 test.c
$ ./a.out
gthread count is 0
x:0, y:1
x:0, y:2
x:0, y:3
x:0, y:4
x:0, y:5
x:0, y:6
x:0, y:7
x:0, y:8
x:0, y:9
参考资料:http://blog.163.com/jiangbowen1_qd/blog/static/61395762201061483929145/
中文帮助手册: