最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Linux多線程編程(一)

 更新時間:2014年08月27日 10:01:12   投稿:hebedich  
linux多線程設計是指基于Linux操作系統(tǒng)下的多線程設計,包括多任務程序的設計,并發(fā)程序設計,網(wǎng)絡程序設計,數(shù)據(jù)共享等。Linux系統(tǒng)下的多線程遵循POSIX線程接口,稱為pthread。

一、什么是線程?

      線程是進程的一個實體,是CPU調度和分派的基本單位,它是比進程更小的能獨立運行的基本單位。線程自己基本上不擁有系統(tǒng)資源,只擁有一點在運行中必不可少的資源(如程序計數(shù)器,一組寄存器和棧),但是它可與同屬一個進程的其他的線程共享進程所擁有的全部資源。

二、什么時候使用多線程?     當多個任務可以并行執(zhí)行時,可以為每個任務啟動一個線程。
三、線程的創(chuàng)建     使用pthread_create函數(shù)。    

#include<pthread.h>
int pthread_create (pthread_t *__restrict __newthread,//新創(chuàng)建的線程ID
			  __const pthread_attr_t *__restrict __attr,//線程屬性
			  void *(*__start_routine) (void *),//新創(chuàng)建的線程從start_routine開始執(zhí)行
			  void *__restrict __arg)//執(zhí)行函數(shù)的參數(shù)

返回值:成功-0,失敗-返回錯誤編號,可以用strerror(errno)函數(shù)得到錯誤信息
四、線程的終止   三種方式線程從執(zhí)行函數(shù)返回,返回值是線程的退出碼線程被同一進程的其他線程取消調用pthread_exit()函數(shù)退出。這里不是調用exit,因為線程調用exit函數(shù),會導致線程所在的進程退出。

一個小例子:

啟動兩個線程,一個線程對全局變量num執(zhí)行加1操作,執(zhí)行五百次,一個線程對全局變量執(zhí)行減1操作,同樣執(zhí)行五百次。

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

int num=0;
void *add(void *arg) {//線程執(zhí)行函數(shù),執(zhí)行500次加法
  int i = 0,tmp;
  for (; i <500; i++)
  {
    tmp=num+1;
    num=tmp;
    printf("add+1,result is:%d\n",num);
  }
  return ((void *)0);
}
void *sub(void *arg)//線程執(zhí)行函數(shù),執(zhí)行500次減法
{
  int i=0,tmp;
  for(;i<500;i++)
  {
    tmp=num-1;
    num=tmp;
    printf("sub-1,result is:%d\n",num);
  }
  return ((void *)0);
}
int main(int argc, char** argv) {
  
  pthread_t tid1,tid2;
  int err;
  void *tret;
  err=pthread_create(&tid1,NULL,add,NULL);//創(chuàng)建線程
  if(err!=0)
  {
    printf("pthread_create error:%s\n",strerror(err));
    exit(-1);
  }
  err=pthread_create(&tid2,NULL,sub,NULL);
  if(err!=0)
  {
    printf("pthread_create error:%s\n",strerror(err));
     exit(-1);
  }
  err=pthread_join(tid1,&tret);//阻塞等待線程id為tid1的線程,直到該線程退出
  if(err!=0)
  {
    printf("can not join with thread1:%s\n",strerror(err));
    exit(-1);
  }
  printf("thread 1 exit code %d\n",(int)tret);
  err=pthread_join(tid2,&tret);
  if(err!=0)
  {
    printf("can not join with thread1:%s\n",strerror(err));
    exit(-1);
  }
  printf("thread 2 exit code %d\n",(int)tret);
  return 0;
}

使用g++編譯該文件(g++ main.cpp -o main)。此時會報錯undefined reference to `pthread_create'。


報這個錯誤的原因是:pthread庫不是linux默認的庫,所以在編譯時候需要指明libpthread.a庫。

解決方法:在編譯時,加上-lpthread參數(shù)。

執(zhí)行結果:


乍一看,結果是對的,加500次,減500次,最后結果為0。但是仔細看所有的輸出,你會發(fā)現(xiàn)有異樣的東西。


    導致這個不和諧出現(xiàn)的原因是,兩個線程可以對同一變量進行修改。假如線程1執(zhí)行tmp=50+1后,被系統(tǒng)中斷,此時線程2對num=50執(zhí)行了減一操作,當線程1恢復,在執(zhí)行num=tmp=51。而正確結果應為50。所以當多個線程對共享區(qū)域進行修改時,應該采用同步的方式。

五、線程同步線程同步的三種方式:

1、互斥量   互斥量用pthread_mutex_t數(shù)據(jù)類型來表示。   

兩種方式初始化,第一種:賦值為常量PTHREAD_MUTEX_INITIALIZER;第二種,當互斥量為動態(tài)分配是,使用pthread_mutex_init函數(shù)進行初始化,使用pthread_mutex_destroy函數(shù)銷毀。  

#include<pthread.h>
int pthread_mutex_init (pthread_mutex_t *__mutex,
			    __const pthread_mutexattr_t *__mutexattr);
int pthread_mutex_destroy (pthread_mutex_t *__mutex);

返回值:成功-0,失敗-錯誤編號 加解鎖加鎖調用pthread_mutex_lock,解鎖調用pthread_mutex_unlock。

#include<pthread.h>
int pthread_mutex_lock (pthread_mutex_t *__mutex);
int pthread_mutex_unlock (pthread_mutex_t *__mutex);


使用互斥量修改上一個程序(修改部分用紅色標出):

pthread_mutex_t mylock=PTHREAD_MUTEX_INITIALIZER;
void *add(void *arg) {
  int i = 0,tmp;
  for (; i <500; i++)
  {
    pthread_mutex_lock(&mylock);
    tmp=num+1;
    num=tmp;
    printf("+1,result is:%d\n",num);
    pthread_mutex_unlock(&mylock);
  }
  return ((void *)0);
}
void *sub(void *arg)
{
  int i=0,tmp;
  for(;i<500;i++)
  {
    pthread_mutex_lock(&mylock);
    tmp=num-1;
    num=tmp;
    printf("-1,result is:%d\n",num);
    pthread_mutex_unlock(&mylock);
  }
  return ((void *)0);
}

2、讀寫鎖   允許多個線程同時讀,只能有一個線程同時寫。適用于讀的次數(shù)遠大于寫的情況。  讀寫鎖初始化:  

#include<pthread.h>
int pthread_rwlock_init (pthread_rwlock_t *__restrict __rwlock,
				__const pthread_rwlockattr_t *__restrict
				__attr);
int pthread_rwlock_destroy (pthread_rwlock_t *__rwlock);

返回值:成功--0,失敗-錯誤編號
 加鎖,這里分為讀加鎖和寫加鎖。
讀加鎖:  

int pthread_rwlock_rdlock (pthread_rwlock_t *__rwlock)


寫加鎖: 

int pthread_rwlock_wrlock (pthread_rwlock_t *__rwlock)


解鎖用同一個函數(shù)

int pthread_rwlock_unlock (pthread_rwlock_t *__rwlock)

3、條件變量條件變量用pthread_cond_t數(shù)據(jù)類型表示。條件變量本身由互斥量保護,所以在改變條件狀態(tài)前必須鎖住互斥量。
條件變量初始化:
第一種,賦值常量PTHREAD_COND_INITIALIZER;第二種,使用pthread_cond_init函數(shù)

int pthread_cond_init (pthread_cond_t *__restrict __cond,
   __const pthread_condattr_t *__restrict
   __cond_attr);int pthread_cond_destroy (pthread_cond_t *__cond);


條件等待
使用pthread_cond_wait等待條件為真。

 pthread_cond_wait (pthread_cond_t *__restrict __cond,
   pthread_mutex_t *__restrict __mutex)

這里需要注意的是,調用pthread_cond_wait傳遞的互斥量已鎖定,pthread_cond_wait將調用線程放入等待條件的線程列表,然后釋放互斥量,在pthread_cond_wait返回時,再次鎖定互斥量。
喚醒線程
pthread_cond_signal喚醒等待該條件的某個線程,pthread_cond_broadcast喚醒等待該條件的所有線程。

int pthread_cond_signal (pthread_cond_t *__cond);
int pthread_cond_broadcast (pthread_cond_t *__cond)


來一個例子,主線程啟動4個線程,每個線程有一個參數(shù)i(i=生成順序),無論線程的啟動順序如何,執(zhí)行順序只能為,線程0、線程1、線程2、線程3。

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <string.h>
#define DEBUG 1

int num=0;
pthread_mutex_t mylock=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t qready=PTHREAD_COND_INITIALIZER;
void * thread_func(void *arg)
{
  int i=(int)arg; 
  int ret;
  sleep(5-i);//線程睡眠,然最先生成的線程,最后蘇醒
  pthread_mutex_lock(&mylock);//調用pthread_cond_wait前,必須獲得互斥鎖
  while(i!=num)
  {
#ifdef DEBUG
    printf("thread %d waiting\n",i);
#endif
    ret=pthread_cond_wait(&qready,&mylock);//該函數(shù)把線程放入等待條件的線程列表,然后對互斥鎖進行解鎖,這兩部都是原子操作。并且在pthread_cond_wait返回時,互斥量再次鎖住。
    if(ret==0)
    {
#ifdef DEBUG
      printf("thread %d wait success\n",i);
#endif
    }else
    {
#ifdef DEBUG
      printf("thread %d wait failed:%s\n",i,strerror(ret));
#endif
    }
  }
  printf("thread %d is running \n",i);
  num++;
  pthread_mutex_unlock(&mylock);//解鎖
  pthread_cond_broadcast(&qready);//喚醒等待該條件的所有線程
  return (void *)0;
}
int main(int argc, char** argv) {
  
  int i=0,err;
  pthread_t tid[4];
  void *tret;
  for(;i<4;i++)
  {
    err=pthread_create(&tid[i],NULL,thread_func,(void *)i);
    if(err!=0)
    {
      printf("thread_create error:%s\n",strerror(err));
      exit(-1);
    }
  }
  for (i = 0; i < 4; i++)
  {
    err = pthread_join(tid[i], &tret);
    if (err != 0)
    {
      printf("can not join with thread %d:%s\n", i,strerror(err));
      exit(-1);
    }
  }
  return 0;
}


在非DEBUG模式,執(zhí)行結果如圖所示:
在DEBUG模式,執(zhí)行結果如圖所示:

在DEBUG模式可以看出,線程3先被喚醒,然后執(zhí)行pthread_cond_wait(輸出thread 3 waiting),此時在pthread_cond_wait中先解鎖互斥量,然后進入等待狀態(tài)。這是thread 2加鎖互斥量成功,進入pthread_cond_wait(輸出thread 2 waiting) ,同樣解鎖互斥量,然后進入等待狀態(tài)。直到線程0,全局變量與線程參數(shù)i一致,滿足條件,不進入條件等待,輸出thread 0 is running。全局變量num執(zhí)行加1操作,解鎖互斥量,然后喚醒所有等待該條件的線程。thread 3 被喚醒,輸出thread 3 wait success。但是不滿足條件,再次執(zhí)行pthread_cond_wait。如此執(zhí)行下去,滿足條件的線程執(zhí)行,不滿足條件的線程等待。

相關文章

  • CentOS7設置定時任務

    CentOS7設置定時任務

    工作中需要開啟一個定時任務,經過一番研究,最終方案如下,這里分享給大家
    2018-08-08
  • Centos7.3安裝部署最新版Zabbix3.4的方法(圖文)

    Centos7.3安裝部署最新版Zabbix3.4的方法(圖文)

    這篇文章主要介紹了Centos7.3安裝部署最新版Zabbix3.4的方法(圖文),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-03-03
  • CentOS 安裝 Mongodb詳解(在線和離線)

    CentOS 安裝 Mongodb詳解(在線和離線)

    這篇文章主要介紹了CentOS 安裝 Mogodb詳解(在線和離線) ,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-01-01
  • linux系統(tǒng)下vim插件安裝介紹

    linux系統(tǒng)下vim插件安裝介紹

    大家好,本篇文章主要講的是linux系統(tǒng)下vim插件安裝介紹,感興趣的同學趕快來看一看吧,對你有幫助的話記得收藏一下,方便下次瀏覽
    2021-12-12
  • Linux使用zip壓縮命令壓縮文件實現(xiàn)方式(排除不需要的文件)

    Linux使用zip壓縮命令壓縮文件實現(xiàn)方式(排除不需要的文件)

    Linux中使用zip命令壓縮文件的方法,包括-r參數(shù)指定壓縮包名,-x參數(shù)排除特定文件,-j只保存文件內容不保存目錄結構等選項
    2026-04-04
  • Linux crontab定時任務配置方法(詳解)

    Linux crontab定時任務配置方法(詳解)

    下面小編就為大家?guī)硪黄狶inux crontab定時任務配置方法(詳解)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2016-11-11
  • Linux編程之PING實現(xiàn)

    Linux編程之PING實現(xiàn)

    這篇文章主要為大家詳細介紹了Linux編程之PING實現(xiàn)的相關資料,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-01-01
  • 在linux下開啟FTP服務方法介紹

    在linux下開啟FTP服務方法介紹

    這篇文章主要介紹了在linux下開啟FTP服務方法介紹,具有一定參考價值,需要的朋友可以了解下。
    2017-11-11
  • 在Linux系統(tǒng)上連接GitHub的方法步驟(適用2025年)

    在Linux系統(tǒng)上連接GitHub的方法步驟(適用2025年)

    在2025年,使用 Linux 系統(tǒng)連接 GitHub 的推薦方式是通過 SSH (Secure Shell) 協(xié)議進行身份驗證,這種方式不僅安全,還能免去每次操作時輸入用戶名和密碼的繁瑣,本文給介紹了詳細的方法步驟,需要的朋友可以參考下
    2025-08-08
  • Linux查看系統(tǒng)版本最實用的三種方法

    Linux查看系統(tǒng)版本最實用的三種方法

    在Linux系統(tǒng)管理和日常運維中,準確獲取操作系統(tǒng)的版本信息是執(zhí)行軟件安裝、腳本兼容性判斷、系統(tǒng)升級以及問題排查等任務的基石,本文將深入探討并詳細對比在Linux環(huán)境下查看系統(tǒng)版本的幾種主流方法,需要的朋友可以參考下
    2025-10-10

最新評論

岗巴县| 西乌珠穆沁旗| 遂昌县| 大庆市| 马关县| 五莲县| 敦化市| 南溪县| 玉树县| 北票市| 安义县| 平南县| 吴堡县| 鄂托克前旗| 花垣县| 三亚市| 澄江县| 黔东| 哈尔滨市| 广东省| 九江市| 平泉县| 玉龙| 勐海县| 增城市| 浦城县| 安阳县| 吉安县| 漾濞| 博罗县| 全南县| 邢台市| 宽甸| 皋兰县| 义马市| 清河县| 商水县| 梅河口市| 文水县| 河间市| 伊川县|