1.使用pthread的理由
2個(gè)字:簡(jiǎn)單
2.pthread組件
thread,
mutex,
condition var
synchronization
3.線程的終止和產(chǎn)生
小例:
#include <pthread/pthread.h>
#include <stdio.h>
#define NUM_THREADS 5
void *PrintHello(void *threadid)
{
long tid;
tid = (long)threadid;
printf("Hello World! It's me, thread #%ld!\n", tid);
pthread_exit(NULL);
}
int main (int argc, char *argv[])
{
pthread_t threads[NUM_THREADS];
int rc;
long t;
for(t=0; t<NUM_THREADS; t++)
{
printf("In main: creating thread %ld\n", t);
rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t);
if (rc)
{
printf("ERROR; return code from pthread_create() is %d\n", rc);
exit(-1);
}
}
pthread_exit(NULL);
return 0;
}
通過(guò)pthread_create來(lái)創(chuàng)建線程
其第一個(gè)參數(shù)為線程id,第二個(gè)為線程屬性,第三個(gè)為線程函數(shù),最后一個(gè)為數(shù)據(jù)參數(shù)
那么線程如何終止呢:
1.從運(yùn)行函數(shù)終止
2.調(diào)用pthread_exit終止
3.調(diào)用pthread_cance
4.進(jìn)程終止
向線程傳遞參數(shù)
#include <pthread/pthread.h>
#include <stdio.h>
#include <string>
#include <iostream>
#define NUM_THREADS 5
struct Data
{
std::string name;
};
Data* data_impl;
void *PrintHello(void* data_ptr)
{
struct Data* data;
data = (Data*)data_ptr;
std::cout<<data->name<<std::endl;
pthread_exit(NULL);
}
int main (int argc, char *argv[])
{
pthread_t threads[NUM_THREADS];
data_impl = new Data[NUM_THREADS];
data_impl[0].name = "T1";
data_impl[1] .name= "T2";
data_impl[2] .name= "T3";
data_impl[3] .name= "T4";
data_impl[4] .name= "T5";
for(int t=0; t<NUM_THREADS; t++)
{
int rc = pthread_create(&threads[t], NULL, PrintHello,&data_impl[t]);
}
pthread_exit(NULL);
delete []data_impl;
return 0;
}
其他相關(guān)線程庫(kù):
1.zthread,
2.opentherad
3.boost therad
4.原生態(tài)的平臺(tái)線程函數(shù)