先看一个例子:pthread1.c
#if defined(WIN32)
#include <windows.h> // void Sleep(DWORD ms)
#define SLEEP(ms) Sleep(ms)
#else if defined(LINUX)
#include <unistd.h> // unsigned int sleep(unsigned int)
#include <stdio.h>
#include <stdlib.h>
#define SLEEP(ms) sleep(ms)
#endif
#include <pthread.h>
/** 作为线程入口的函数 */
void * print_message_function(void *ptr)
{
SLEEP(5);
char *message;
message = (char *) ptr;
printf("%s \n", message);
return NULL;
}
int main(int argc, char* argv[])
{
pthread_t thread1, thread2;
char *message1 = "Thread 1";
char *message2 = "Thread 2";
int iret1, iret2;
// 成功创建线程时返回零
iret1 = pthread_create(&thread1, NULL, &print_message_function, (void*) message1);
iret2 = pthread_create(&thread2, NULL, &print_message_function, (void*) message2);
/* 等待两个线程结束 -- 同步
* 如果不同步,则有可能主线程的return先执行,导致子线程未完成任务而先完蛋
* 可以启用Sleep试试。
*/
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
printf("Thread 1 returns: %d\n", iret1);
printf("Thread 2 returns: %d\n", iret2);
return 0;
}
* C++ compiler: g++ -lpthread pthread1.c
结束线程的方法: * pthread_exit
* 让函数自己返回
* exit 停止整个进程(当然包括所有的线程)
创建线程的函数原型: