pthread多线程编程

线程函数需要声明为void*类型。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <pthread.h>

/*
* The function to be executed by the thread should take a
* void* parameter and return a void* exit status code.
*/
void *thread_function(void *arg){
// Cast the parameter into what is needed.
int *incoming=(int*)arg;

// Do whatever is necessary using *incoming as the argument.

// The thread terminates when this function returns.
return NULL;
}

int main(void){
pthread_t thread_ID;
void *exit_status;
int value;

// Put something meaningful into value.
value=42;

// Create the thread, passing &value for the argument.
pthread_create(&thread_ID,NULL,thread_function,&value);

// The main program continues while the thread executes.

// Wait for the thread to terminate.
pthread_join(thread_ID,&exit_status);

// Only the main thread is running now.
return 0;
}

重要函数:

  1. Create a new thread

pthread_create()

1
2
3
4
5
6
int pthread_create(
pthread_t *tid, //thread ID
const pthread_attr_t *attr, //thread attributes
void *(*start_routine)(void*), //pointer to function to execute
void *arg //argument to function
);

Return value: 0 if successful. Error code from otherwise.

Notes: Use a structure to pass multiple arguments to the start routine.

  1. Wait for a thread to terminate

pthread_join

1
2
3
4
int pthread_join(
pthread_t tid, //wait for a thread to terminate
void **status; //thread ID to wait for
);

Return value: 0 for success. Error code from otherwise.

Notes: Once a thread is joined, the thread no longer exists, its thread ID is no longer valid, and it cannot be joined with any other thread.

  1. Get my own thread ID

pthread_self

1
pthread_t pthread_self();

Return value: The ID of the thread that called this function.