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

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

先看一个简单实例:

Linux下的多线程编程(简单入门)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

 

原文链接: https://www.cnblogs.com/pdeagle/archive/2011/10/09/2203829.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

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

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/33859

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月8日 上午10:54
下一篇 2023年2月8日 上午10:54

相关推荐