歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 用Pthreads進行共享內存編程----HelloWorld

用Pthreads進行共享內存編程----HelloWorld

日期:2017/3/1 9:58:23   编辑:Linux編程

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

Copyright © Linux教程網 All Rights Reserved