PDEagle的技术博客

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

这里总结以下Linux下的C/C++编程:

先看一个简单实例:

View Code
 1 #include <iostream>
 2 #include <stdio.h>
 3 #include <pthread.h>
 4 
 5 using namespace std;
 6 
 7 void* thread(void *arg){
 8     int i;
 9     for(i=0;i<100;i++){
10         cout<<"thread: "<<i<<endl;
11     }   
12     return ((void *)0);
13 }
14 
15 
16 int main(){
17     pthread_t id; 
18     int i,ret;
19     ret=pthread_create(&id,NULL, thread,NULL);
20     if(ret != 0){ 
21         cout << "Create pthread error!" << endl;
22         return 1;
23     }   
24     for(i=0;i<100;i++){
25         cout << "main: " << i << endl;
26     }   
27     pthread_join(id,NULL);
28     return 0;
29 }

 

执行线程操作的函数需要是void* fun(void*)类型的,这是因为我们将在pthread_create函数中将该函数的函数指针传入。

pthread_create函数的标准定义是:

 

1 extern int pthread_create __P (pthread_t *__thread, __const pthread_attr_t *__attr, void *(*__start_routine) (void *), void *__arg));

 

 

很复杂的样子。这里第三个参数就是要传入的函数;第二个与第四个参数我们都设为NULL,它们事实上分别对应线程的属性和__start_routine函数的参数。其中线程属性如果设为NULL表示是正常的属性。如果成功创建线程,该函数将返回0,否则表示出错。

 

注意到原程序中有一个pthread_join函数,这个函数的作用是等待该线程结束。该函数有两个参数,第一个参数表示线程ID,第二个是一个void **类型对象,它将存储目标线程结束返回的值。需要注意的是,一个线程不能被多个线程等待结束,不然会抛错。

1 extern int pthread_join __P (pthread_t __th, void **__thread_return);

 

另外,需要在编译时加入库:-lpthread

 

posted on 2011-10-09 16:15  PDEagle  阅读(299)  评论(1)    收藏  举报