1.pth_hello.c
#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;
}
2.Makefile
pth_hello:
gcc -g -Wall -o pth_hello pth_hello.c -lpthread
clean:
rm -rf pth_hello
3.编译与运行
rocky@rocky-Inspiron-3421:~/zzq/pthread$ make
gcc -g -Wall -o pth_hello pth_hello.c -lpthread
rocky@rocky-Inspiron-3421:~/zzq/pthread$ ./pth_hello 5
Hello from thread 2 of 5
Hello from thread 0 of 5
Hello from the main thread
Hello from thread 3 of 5
Hello from thread 4 of 5
Hello from thread 1 of 5
4.说明
(1)在Pthreads程序中,全局变量被所有线程所共享,而在函数中申明的局部变量则通常由执行该函数的线程所私有。如果多个线程都要运行同一个函数,则每个线程都拥有自己的私有局部变量和函数参数的副本。
未完待续...