溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

linux中pthread_create的使用方法

發(fā)布時間:2020-07-22 16:02:43 來源:億速云 閱讀:218 作者:小豬 欄目:服務器

這篇文章主要講解了linux中pthread_create的使用方法,內(nèi)容清晰明了,對此有興趣的小伙伴可以學習一下,相信大家閱讀完之后會有幫助。

pthread_create函數(shù)

函數(shù)簡介

  pthread_create是UNIX環(huán)境創(chuàng)建線程函數(shù)

頭文件

  #include<pthread.h>

函數(shù)聲明

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

返回值

  若成功則返回0,否則返回出錯編號

參數(shù)

  第一個參數(shù)為指向線程標識符的指針。

  第二個參數(shù)用來設置線程屬性。

  第三個參數(shù)是線程運行函數(shù)的地址。

  最后一個參數(shù)是運行函數(shù)的參數(shù)。

注意

  在編譯時注意加上-lpthread參數(shù),以調(diào)用靜態(tài)鏈接庫。因為pthread并非Linux系統(tǒng)的默認庫。

pthread_join函數(shù)

函數(shù)簡介

  函數(shù)pthread_join用來等待一個線程的結(jié)束。

函數(shù)原型為:

  extern int pthread_join __P (pthread_t __th, void **__thread_return);

參數(shù):

  第一個參數(shù)為被等待的線程標識符

  第二個參數(shù)為一個用戶定義的指針,它可以用來存儲被等待線程的返回值。

注意

    這個函數(shù)是一個線程阻塞的函數(shù),調(diào)用它的函數(shù)將一直等待到被等待的線程結(jié)束為止,當函數(shù)返回時,被等待線程的資源被收回。如果執(zhí)行成功,將返回0,如果失敗則返回一個錯誤號。

例子:

#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>

/* 聲明結(jié)構(gòu)體 */
struct member
{
  int num;
  char *name;
};

/* 定義線程pthread */
static void * pthread(void *arg)
{
  struct member *temp;

  /* 線程pthread開始運行 */
  printf("pthread start!\n");

  /* 令主線程繼續(xù)執(zhí)行 */
  sleep(2);

  /* 打印傳入?yún)?shù) */
  temp = (struct member *)arg;
  printf("member->num:%d\n",temp->num);
  printf("member->name:%s\n",temp->name);

  return NULL;
}

/* main函數(shù) */
int main(int agrc,char* argv[])
{
  pthread_t tidp;
  struct member *b;

  /* 為結(jié)構(gòu)體變量b賦值 */
  b = (struct member *)malloc(sizeof(struct member));
  b->num=1;
  b->name="mlq";

  /* 創(chuàng)建線程pthread */
  if ((pthread_create(&tidp, NULL, pthread, (void*)b)) == -1)
  {
    printf("create error!\n");
    return 1;
  }

  /* 令線程pthread先運行 */
  sleep(1);

  /* 線程pthread睡眠2s,此時main可以先執(zhí)行 */
  printf("mian continue!\n");

  /* 等待線程pthread釋放 */
  if (pthread_join(tidp, NULL))
  {
    printf("thread is not exit...\n");
    return -2;
  }

  return 0;
}

編譯與執(zhí)行結(jié)果

    編譯與執(zhí)行結(jié)果如下圖所示,可以看到主線程main和線程pthread交替執(zhí)行。也就是說是當我們創(chuàng)建了線程pthread之后,兩個線程都在執(zhí)行,證明創(chuàng)建成功。另外,可以看到創(chuàng)建線程pthread時候,傳入的參數(shù)被正確打印。

linux中pthread_create的使用方法

看完上述內(nèi)容,是不是對linux中pthread_create的使用方法有進一步的了解,如果還想學習更多內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI