Jiwu Bu

  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  32 随笔 :: 0 文章 :: 25 评论 :: 0 Trackbacks
 1 #include <stdio.h>       /* standard I/O routines                 */
 2 #include <pthread.h>     /* pthread functions and data structures */
 3 #include <unistd.h>      /* head file for sleep function */
 4 
 5 /* global mutex for our program. assignment initializes it */
 6 pthread_mutex_t a_mutex = PTHREAD_MUTEX_INITIALIZER;
 7 
 8 /* function to be executed by the new thread */
 9 void* do_loop(void* data)
10 {
11     int me = *((int*)data);     /* thread identifying number */
12     int rc; /* contain mutex lock/unlock results */
13     
14     /* lock the mutex, to assure exclusive */
15     rc = pthread_mutex_lock(&a_mutex);
16     
17     for (int i=0; i< 4; i++
18     {
19         printf("'%d' - Got '%d'\n", me, i);
20         sleep(1);
21     }
22 
23     /* unlock mutex */
24     rc = pthread_mutex_unlock(&a_mutex);
25     
26     /* terminate the thread */
27     pthread_exit(NULL);
28 }
29 
30 /* like any CPlusPlus program, program's execution begins in main */
31 /*g++ -o Thread Thread.cpp -lpthread*/
32 int main(int argc, char* argv[])
33 {
34     int        thr_id;         /* thread ID for the newly created thread */
35     pthread_t  p_thread1;       /* thread's structure                     */
36     pthread_t  p_thread2;       /* thread's structure                     */
37     int        a = 1;  /* thread 1 identifying number            */
38     int        b = 2;  /* thread 2 identifying number            */
39 
40     /* create a new thread that will execute 'do_loop()' */
41     thr_id = pthread_create(&p_thread1, NULL, do_loop, (void*)&a);
42     
43     /* create a new thread */
44     thr_id = pthread_create(&p_thread2, NULL, do_loop, (void*)&b);
45     
46     /*wait until sub thread exit*/
47     pthread_join(p_thread1, NULL);
48     pthread_join(p_thread2, NULL);
49 
50     return 0;
51 }
52 

编译: gcc -o pthread pthread.c  -lpthread


Linux下线程与信号量例子
posted on 2009-01-18 14:00 bujiwu 阅读(283) 评论(0)  编辑 收藏 引用 所属分类: Linux

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理