#include <pthread.h>
int pthread_create(pthread_t *restrict tidp,
const pthread_attr_t *restrict attr,
void *(*start_rtn)(void),
void *restrict arg);
Returns: 0 if OK, error number on failure
第一個參數為指向線程標識符的指針。
第二個參數用來設置線程屬性。第三個參數是線程運行函數的起始地址。
最后一個參數是運行函數的參數。
ps:
編譯的時候,一定要加上-lpthread選項,不然會報錯:undefined reference to `pthread_create'。
下面來看看pthread_create的聲明:
#include<pthread.h>
int pthread_create(pthread_t *thread, pthread_addr_t *arr,
void* (*start_routine)(void *), void *arg);
- thread :用於返回創建的線程的ID
- arr : 用於指定的被創建的線程的屬性,上面的函數中使用NULL,表示使用默認的屬性
- start_routine : 這是一個函數指針,指向線程被創建后要調用的函數
- arg : 用於給線程傳遞參數,在本例中沒有傳遞參數,所以使用了NULL
簡單的線程程序
#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
)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);
rc = pthread_create(&
thread
[t], NULL, PrintHello, (
void
*)t);
if
(rc)
{
printf
(
"ERROR; return code is %d\n"
, rc);
return
EXIT_FAILURE;
}
}
for
( t = 0; t < NUM_THREADS; t++)
pthread_join(
thread
[t], NULL);
return
EXIT_SUCCESS;
}