int pthread_create (pthread_t *pThread, const pthread_attr_t *pAttr, void * (*start_routine)(void *),void *arg);
函数说明:创建一个线程;
参数说明:
参数一:线程id,创建线程时,为每一个线程分配一个id。
参数二:线程属性,后面详细介绍线程属性。
参数三:线程函数,注意该函数返回值必须为void* 且参数同样也只能是void*。
参数四:传递给线程函数的参数。
简单的线程程序
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#define NUM_THREADS 8
void *PrintHello(void *args)
{
int thread_arg;
sleep(1);
thread_arg = (int)(*((int*)args));
printf("Hello from thread %d\n", thread_arg);
return NULL;
}
int main(void)
{
int rc,t;
pthread_t thread[NUM_THREADS];
for( t = 0; t < NUM_THREADS; t++)
{
printf("Creating thread %d\n", t);
//此处t变量的用法是方便大家调测代码的写法,实际使用会有问题,因为这个t是局部变量,
//函数执行完后马上释放,大家传递参数时需要使用全局变量或malloc出来的变量。
rc = pthread_create(&thread[t], NULL, PrintHello, &t);
if (rc)
{
printf("ERROR; return code is %d\n", rc);
return EXIT_FAILURE;
}
}
sleep(5);
for( t = 0; t < NUM_THREADS; t++)
pthread_join(thread[t], NULL);
return EXIT_SUCCESS;
}
$ gcc thread_test.c -o thread_test -std=c99 -pthread
$ ./thread_test
Creating thread 0
Creating thread 1
Creating thread 2
Creating thread 3
Creating thread 4
Creating thread 5
Creating thread 6
Creating thread 7
Hello from thread 8
Hello from thread 8
Hello from thread 8
Hello from thread 8
Hello from thread 8
Hello from thread 8
Hello from thread 8
Hello from thread 8