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
先看一个简单实例:
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
相关文章推荐
- Linux中安装MongoDB及简单入门
- Linux简单入门(十四)SHELL 脚本
- linux下使用select I/O复用和多线程编程实现简单的TCP服务器
- Linux 下GDB的使用之简单入门
- Linux简单入门(五)系统的远程登录
- Linux简单入门(十五)系统日常管理
- linux简单命令--shell入门命令
- pthread/Linux 简单多线程编程
- [Linux学习]一个简单的Makefile入门
- Linux网络编程-简单的客户端和服务器通讯程序开发入门(2)
- Linux系统分析入门--简单汇编代码分析
- Linux简单入门(六)文件与目录管理
- 最简单的linux命令入门
- Linux 下GDB的使用之简单入门
- Linux简单入门(十六)LAMP环境搭建
- Linux Qt下简单的多线程编程
- Linux简单入门(七)系统用户以及用户组管理
- Linux简单入门(十七)LNMP环境搭建
- linux 入门简单命令
- linux上简单的JNI入门实例