0
点赞
收藏
分享

微信扫一扫

并行程序设计 pthread

配置环境

pthread是c的扩展库,需要配置环境,不过vscode的mingw里面本来就有,谢谢呢^_^

cd “d:\sylvia\文件夹等等等” ;
if ($?) { g++ helloworld.cpp -o helloworld } ; //编译
if ($?) { .\helloworld 线程数} //运行

常用变量声明及函数

my_rank 当前线程序号,局部变量
thread_count 总线程数,全部变量

从命令行读取线程数

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

strtol函数: 把参数 str 所指向的字符串根据给定的 base 转换为一个长整数(类型为 long int 型)

long strtol (
const char* number_p /* in -- 要转换为长整数的字符串。*/,
char** end_p /* out 对类型为 char* 的对象的引用,其值由函数设置为 str 中数值后的下一个字符。*/,
int base /* in  必须介于 2 和 36(包含)之间,或者是特殊值 0。*/ );

用long很奇怪,但这个库里大部分变量类型都是long,但是long long也行,long好像还报错??

启动线程

pthread_t是线程对象的数据类型,一般pthread_t* thread_handles来创建一个变长的线程对象数组,然后new分配长度,然后用pthread_create(&thread_handles[thread], NULL, Hello, (void*)thread);来创建线程
pthread_create是创建线程的API

int pthread_create (
pthread_t* thread_p /*out 要创建的线程*/ ,
const pthread_attr_t* attr_p /* in 不知道 */ ,
void* (*start_routine ) ( void* ) /* in 线程函数? */ ,
void* arg_p /* in  不知道*/ ) ;

线程函数

void* thread_function( void* args_p );

合并(停止)线程

int pthread_join (
pthread_t thread /*in */ ,
void** ret_val_p /* out */ ) 

Hello World

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
int thread_count;
void* Hello(void* rank){
	long long my_rank = (long long)rank;
	printf("Hello from thread %ld of %d\n", my_rank, thread_count);
	return NULL;
}

int main(int argc, char* argv[]) {
	long long thread;
	pthread_t* thread_handles; //线程对象,可变数组
	thread_count = strtol(argv[1], NULL, 10);//从命令行读取线程数
	thread_handles = new pthread_t[thread_count];//分配长度
	
	for(thread = 0; thread < thread_count; thread++){
		pthread_create(&thread_handles[thread], NULL, Hello, (void*)thread);
	}
		
	printf("Hello from the main thread\n");
	for(thread = 0; thread < thread_count; thread++)
		pthread_join(thread_handles[thread], NULL);//合并线程
		
	free(thread_handles);
	return 0;
}


在这里插入图片描述

举报

相关推荐

0 条评论