以前都是Windows編程,一直說看看Linux下的線程編程,有空了,回顧一下吧。
頭文件
Linux下線程相關(guān)函數(shù)都在頭文件 <pthread.h> 中,該頭文件中的相關(guān)函數(shù)在專門的線程庫libpthread中,編譯的時候需要加上 -lpthread 選項
一些函數(shù)
pthread_self獲取當前線程
pthread_self(void) //返回類型為: pthread_t
pthread_equal判斷線程是否相同相等
pthread_equal(pthread_t , pthread_t) // 返回int,非0則相等
pthread_create創(chuàng)建線程
int pthread_create(pthread_t* pthread, const pthread_attr_t*, void* (*start_routine )(void*), void* arg )
成功返回0,錯誤號表示失敗
- pthread_t 類型變量的thread,線程的標識
- pthread_attr 線程屬性設置,控制線程與程序其他部分交互方式,常設為NULL,默認線程屬性
- start_routine 線程函數(shù)指針,是線程要執(zhí)行的代碼,參數(shù)為void(*)
- arg 傳遞給start_routine的參數(shù)(如果需要傳遞多個參數(shù),常設為一個結(jié)構(gòu)體,將結(jié)構(gòu)體指針傳遞給線程)
pthread_cancle線程終止
int pthread_cancle(pthread_t thread)
成功返回0
pthread_join 等待線程終止
int pthread_join(pthread_t thread, void **ptr)
成功返回0,否則失敗
ptr 為返回碼,常設為 NULL
代碼
用gcc編譯的話,得加上 -lpthread -lstdc++
#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
#include <string.h> //strerror
#include <pthread.h>
using namespace std;
static int number = 0;
void printids(const char * s)
{
pid_t pid;
pthread_t tid;
pid = getpid(); //獲取進程id
tid = pthread_self(); //獲取線程id
cout << s << " pid " << (unsigned long)pid << " tid " << (unsigned long)tid << endl;
}
void *run(void* nu) //線程函數(shù),參數(shù)得為void*
{
int num = *((int*)nu);
printids("run1 thread:");
cout << "get num from param in run1 " << num << endl;
return ((void *)0); //void* 類型的空指針
}
void *run2(void*)
{
for(int i = 0; i < 3; ++i)
{
cout << "run2 thread number : " << ++number << endl;
sleep(1);
}
return NULL;
}
int main(int argc, char* argv[])
{
//pthread_t pthread_self();
/*pthread_t t1;
cout << pthread_self() << endl;
cout << (pthread_t)t1 << endl;*/
pthread_t ntid, tid2; //線程標識
int num=5;
int err;
//創(chuàng)建第一個線程,線程函數(shù)run,線程函數(shù)的參數(shù)為num.
err = pthread_create(&ntid, NULL, run,(void*)(&num));
sleep(1);
if(0 != err)
{
cout << "cannot create thread: " << strerror(err) << endl;
exit(1);
}
//創(chuàng)建第二個線程,線程函數(shù)為run2, 函數(shù)沒有參數(shù)
pthread_create(&tid2, NULL, run2, NULL);
//加上join,主線程main 會讓線程2,也就是run2函數(shù)執(zhí)行完畢后,才會輸出最后一句
pthread_join(tid2, NULL); //如果不加上pthread_join,可能會看不到run2函數(shù)執(zhí)行,main線程先執(zhí)行完畢
cout << "main thread number : " << number << endl;
return 0;
}