pthread_create函數的詳細講解(包括向線程函數傳遞參數詳解)

pthread_create是UNIX環境創建線程函數

頭文件

  #include<pthread.h>

函數聲明

  int pthread_create(pthread_t*restrict tidp,const pthread_attr_t *restrict_attr,void*(*start_rtn)(void*),void *restrict arg);

返回值

  若成功則返回0,否則返回出錯編號
  返回成功時,由tidp指向的內存單元被設置爲新創建線程的線程ID。attr參數用於制定各種不同的線程屬性。新創建的線程從start_rtn函數的地址開始運行,該函數只有一個萬能指針參數arg,如果需要向start_rtn函數傳遞的參數不止一個,那麼需要把這些參數放到一個結構中,然後把這個結構的地址作爲arg的參數傳入。
  linux下用C開發多線程程序,Linux系統下的多線程遵循POSIX線程接口,稱爲pthread。
  由 restrict 修飾的指針是最初唯一對指針所指向的對象進行存取的方法,僅當第二個指針基於第一個時,才能對對象進行存取。對對象的存取都限定於基於由 restrict 修飾的指針表達式中。 由 restrict 修飾的指針主要用於函數形參,或指向由 malloc() 分配的內存空間。restrict 數據類型不改變程序的語義。 編譯器能通過作出 restrict 修飾的指針是存取對象的唯一方法的假設,更好地優化某些類型的例程。

參數

  第一個參數爲指向線程標識符的指針。
  第二個參數用來設置線程屬性。
  第三個參數是線程運行函數的起始地址。
  最後一個參數是運行函數的參數。
  另外,在編譯時注意加上-lpthread參數,以調用靜態鏈接庫。因爲pthread並非Linux系統的默認庫

示例

  打印線程 IDs
  #include <pthread.h>
  #include <stdlib.h>
  #include <stdio.h>
  #include <unistd.h>
  #include <string.h>
  pthread_t ntid;
  void printids(const char *s)
  {
  pid_t pid;
  pthread_t tid;
  pid = getpid();
  tid = pthread_self();
  printf("%s pid %u tid %u (0x%x)\n", s,
  (unsigned int)pid, (unsigned int)tid, (unsigned int)tid);
  } void *thr_fn(void *arg)
  {
  printids("new thread: ");
  return((void *)0);
  }
  int main(void)
  {
  int err;
  err = pthread_create(&ntid, NULL, thr_fn, NULL);
  if (err != 0)
  printf("can't create thread: %s\n", strerror(err));
  printids("main thread:");
  sleep(1);
  exit(0);
  }
  $ gcc main.c -lpthread

  $ ./a.out

向線程函數傳遞參數詳解:

向線程函數傳遞參數分爲兩種:

(1)線程函數只有一個參數的情況:直接定義一個變量通過應用傳給線程函數。

例子:

#include <iostream>
#include <pthread.h>
using namespace std;
pthread_t thread;
void fn(void *arg)
{
    int i = *(int *)arg;
    cout<<"i = "<<i<<endl;
    return ((void *)0);
}
int main()
{
    int err1;
    int i=10;
   err1 = pthread_create(&thread, NULL, fn, &i);
    pthread_join(thread, NULL);
}
2、線程函數有多個參數的情況:這種情況就必須申明一個結構體來包含所有的參數,然後在傳入線程函數,具體如下:

例子:

首先定義一個結構體:

struct  parameter

{

  int size,

  int count;

。。。。。

。。。 
};

然後在main函數將這個結構體指針,作爲void *形參的實際參數傳遞

struct parameter arg;

通過如下的方式來調用函數:
pthread_create(&ntid, NULL, fn,& (arg));
函數中需要定義一個parameter類型的結構指針來引用這個參數 

void fn(void *arg)
{
    int i = *(int *)arg;
    cout<<"i = "<<i<<endl;
    return ((void *)0);
}

void thr_fn(void *arg)
{
       struct parameter *pstru;
       pstru = ( struct parameter *) arg;
       然後在這個函數中就可以使用指針來使用相應的變量的值了。
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章