pthread_create函式詳解(向執行緒函式傳遞引數)
阿新 • • 發佈:2018-12-12
一、pthread_create函式:
1、簡介:pthread_create是UNIX環境建立執行緒的函式
2、標頭檔案:#include <pthread.h>
3、函式宣告:
int pthread_create(pthread_t* restrict tidp,const pthread_attr_t* restrict_attr,void* (*start_rtn)(void*),void *restrict arg);
4、輸入引數:(以下做簡介,具體參見例項一目瞭然)
(1)tidp:事先建立好的pthread_t型別引數。成功時tidp指向的記憶體單元被設定為新建立執行緒的執行緒ID。
(2)attr:用於定製各種不同的執行緒屬性。APUE的12.3節討論了執行緒屬性。通常直接設為NULL。
(3)start_rtn:新建立執行緒從此函式開始執行。無引數是arg設為NULL即可。
(4)arg:start_rtn函式的引數。無引數時設為NULL即可。有引數時輸入引數的地址。當多於一個引數時應當使用結構體傳入。(以下舉例)
5、返回值:成功返回0,否則返回錯誤碼。
舉例如下:
二、不向執行緒函式傳遞引數:
#include "apue.h" #include <pthread.h> #include "apueerror.h" #include <iostream> #include <string> using namespace std; pthread_t ntid; void printids(const char *s){ pid_t pid; pthread_t tid; pid = getpid(); tid = pthread_self(); printf("%s pid %lu tid %lu (0x%lx)\n", s, (unsigned long)pid, (unsigned long)tid, (unsigned long)tid); } void *thr_fn(void *arg){ printids("new thread: "); cout << "Change to C++ code!!" << endl; return((void *)0); } int main(void){ int err; err = pthread_create(&ntid, NULL, thr_fn, NULL); if (err != 0) err_exit(err, "can't create thread"); printids("main thread:"); sleep(1); exit(0); }
三、向執行緒函式傳遞一個引數:
#include "apue.h" #include <pthread.h> #include "apueerror.h" #include <iostream> #include <string> using namespace std; pthread_t ntid; void printids(const char *s){ pid_t pid; pthread_t tid; pid = getpid(); tid = pthread_self(); printf("%s pid %lu tid %lu (0x%lx)\n", s, (unsigned long)pid, (unsigned long)tid, (unsigned long)tid); } struct Param { int a; int b; int c; }; void *thr_fn( void *arg ) { int tmp = *(int *)arg; cout << "tmp=" << tmp << endl; printids("new thread: "); cout << "Change to C++ code!!" << endl; return((void *)0); } int main(void){ int err; int num = 123; err = pthread_create(&ntid, NULL, thr_fn, &num); if (err != 0) err_exit(err, "can't create thread"); printids("main thread:"); sleep(1); exit(0); }
四、向執行緒函式傳遞兩個或以上的引數:
#include "apue.h"
#include <pthread.h>
#include "apueerror.h"
#include <iostream>
#include <string>
using namespace std;
pthread_t ntid;
void printids(const char *s){
pid_t pid;
pthread_t tid;
pid = getpid();
tid = pthread_self();
printf("%s pid %lu tid %lu (0x%lx)\n", s, (unsigned long)pid,
(unsigned long)tid, (unsigned long)tid);
}
struct Param {
int a;
int b;
int c;
};
void *thr_fn(void *arg) {
Param tmp = *(Param *)arg;
cout << "tmp.a=" << tmp.a << endl;
cout << "tmp.b=" << tmp.b << endl;
cout << "tmp.c=" << tmp.c << endl;
printids("new thread: ");
cout << "Change to C++ code!!" << endl;
return((void *)0);
}
int main(void){
int err;
int num = 123;
Param param1;
param1.a = 11;
param1.b = 22;
param1.c = 33;
err = pthread_create(&ntid, NULL, thr_fn, ¶m1);
if (err != 0)
err_exit(err, "can't create thread");
printids("main thread:");
sleep(1);
exit(0);
}