用Pthreads进行共享内存编程----HelloWorld

1、编译

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

2、运行

./pth_hello <number of threads>

例:运行4个线程,./pth_hello 4

3、源代码

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

int thread_count;

void * Hello(void * rank);

int main(int argc, char * argv[])
{
    long thread;
	pthread_t * thread_handles;

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

	thread_handles = malloc(thread_count * sizeof(pthread_t));

	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;
}

void * Hello(void * rank)
{
    long my_rank = (long)rank;
	printf("Hello from thread %ld of %d\n", my_rank, thread_count);
	return NULL;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值