• <li id="00i08"><input id="00i08"></input></li>
  • <sup id="00i08"><tbody id="00i08"></tbody></sup>
    <abbr id="00i08"></abbr>
  • 新聞中心

    EEPW首頁 > 嵌入式系統 > 設計應用 > Linux多線程同步方法

    Linux多線程同步方法

    作者: 時間:2014-10-17 來源:網絡 收藏

      以下是線程的幾種同步方式:

    本文引用地址:http://www.czjhyjcfj.com/article/264051.htm

    linux操作系統文章專題:linux操作系統詳解(linux不再難懂)

      1、 。

      通過使用pthread的互斥接口保護數據,確保同一時間只有一個線程訪問數據。從本質上講是一把鎖,在訪問共享資源前對進行加鎖,在訪問完成后釋放互斥量上的鎖。如下例所示,就是互斥量對共享數據的操作:

      #include

      #include

      int value = 5;//共享變量

      pthread_mutex_t mutex;//互斥變量

      void *mythread1();

      void mainshow();

      int main()

      {

      int retval;

      pthread_t tid1;

      retval = pthread_create(&tid1,NULL,mythread1,&value);//創建線程

      if(retval != 0){printf(“Can not create mythread1n”);

      mainshow();

      retval = pthread_join(&tid1,NULL);//等待線程mythread1結束

      if(retval != 0){printf(“Can not join with mythread.n”);

      printf(“value = %dn”,value);

      return 0;

      }

      void *mythread1()

      {

      int retval;

      retval = pthread_mutex_lock(&mutex);//上鎖

      value = value + 1;//對共享變量的操作

      printf("value = %dn",value);

      retval = pthread_mutex_unlock(&mutex);//解鎖

      pthread_exit((void *)0);

      }

      void myshow()

      {

      int retval;

      retval = pthread_mutex_lock(&mutex);//上鎖

      value = value + 1;//對共享變量的操作

      printf(“value = %dn”,value);

      pthread_mutex_unlock(&mutex);//解鎖

      }

      2、信號量

      該信號量是Posix提供的基于內存的信號量,它們由應用程序分配信號量的內存空間。如下例所示,就是信號量對共享數據的操作:

      #include

      #include

      #include

      int value = 5;

      sem_t sem1,sem2;

      void mainshow();

      void *mythread();

      int main()

      {

      int retval;

      pthread_t tid;

      retval = sem_init(&sem1,0,0);

      retval = sem_init(&sem2,0,1);

      retval =pthread_create(&tid,NULL,mythread,NULL);

      mainshow();

      pthread_join(tid,NULL);

      printf("value3 = %dn",value);

      return 0;

      }

      void *mythread()

      {

      int retval;

      retval = sem_wait(&sem1);

      value = value + 1;

      printf("value1 = %dn",value);

      retval = sem_post(&sem2);

      pthread_exit((void *) 0);

      }

      void mainshow()

      {

      int retval;

      retval = sem_wait(&sem2);

      value = value + 1;

      printf("value2 = %dn",value);

      retval = sem_post(&sem1);

      }

    linux操作系統文章專題:linux操作系統詳解(linux不再難懂)

    linux相關文章:linux教程




    關鍵詞: Linux 多線程 互斥量

    評論


    相關推薦

    技術專區

    關閉
    主站蜘蛛池模板: 洱源县| 刚察县| 洛隆县| 临沂市| 光山县| 泾川县| 永春县| 屏山县| 陵川县| 民权县| 彭州市| 建湖县| 边坝县| 宜兴市| 鞍山市| 沧源| 新安县| 孝昌县| 甘谷县| 泸溪县| 通化县| 黄浦区| 平江县| 宝兴县| 娄底市| 瑞昌市| 旅游| 海原县| 桐梓县| 胶州市| 黑水县| 阳曲县| 屯留县| 三亚市| 大城县| 博罗县| 龙海市| 正阳县| 大冶市| 四平市| 历史|