pthread库实现简单并行程序:Hello

发布时间 2023-03-29 18:31:18作者: 空空小谢
  • 头文件 pthread.h

获取线程数量:

将字符串转化为10进制数代码:

thread_count=strtol(argv[1],NULL,10);

其语法格式为:

long strtol(
const char* number_p //in,输入字符
char**        end_p      //out,结束
int              base        //in);进制数,我们的程序转化为10进制数字
  • 显示启动线程

显示地启动线程,并且构造能存储线程信息的数据结构;

为每个线程的pthread_t对象分配内存,pthread_t数据结构用来存储线程的专有信息

thread_handles = malloc(thread_count*sizeof(thread_t));//存储线程信息
  • 全部程序入下
 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 #include<pthread.h>
 4 
 5 int thread_cout;
 6 void* Hello(void* rank);
 7 
 8 
 9 int main(int argc,char* argv[]){
10     long thread;
11     pthread_t* thread_heandles;
12     thread_cout=strtol(argv[1],NULL,10);
13 
14     thread_heandles=malloc(thread_cout*sizeof(pthread_t));
15 
16     for (thread = 0; thread < thread_cout; thread++)
17     {
18         pthread_create(& thread_heandles[thread],NULL,Hello,(void*)thread);
19 
20     }
21 
22     printf("Hello from the main thread. \n");
23 
24     for(thread = 0; thread < thread_cout; thread++){
25         pthread_join(thread_heandles[thread],NULL);
26     }
27     
28     free(thread_heandles);
29 
30 
31     printf("你好hello!");
32 
33     return 0;
34 }
35 
36 
37 
38 void * Hello(void* rank){
39     long my_rank=(long)rank;
40     printf("Hello for thread %d of %d \n",my_rank,thread_cout);
41     return NULL;
42 }

 

在mac或者linux系统下,通过如下命令在命令行中编译:

gcc -g -Wall -o pth_hello hello.c -lpthread

然后通过如下命令进行运行

./pth_hello <number of threads>

例如,我们创建5个线程的命令如下:

./pth_hello 5

那么,我们的终端输出如下