您的位置:首页 > 运维架构 > Linux

Linux下的多线程编程(简单入门)

2011-10-09 16:15 295 查看
这里总结以下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++){
cout<<"thread: "<<i<<endl;
}
return ((void *)0);
}

int main(){
pthread_t id;
int i,ret;
ret=pthread_create(&id,NULL, thread,NULL);
if(ret != 0){
cout << "Create pthread error!" << endl;
return 1;
}
for(i=0;i<100;i++){
cout << "main: " << i << endl;
}
pthread_join(id,NULL);
return 0;
}

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

pthread_create函数的标准定义是:

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 **类型对象,它将存储目标线程结束返回的值。需要注意的是,一个线程不能被多个线程等待结束,不然会抛错。

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

另外,需要在编译时加入库:-lpthread
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: