多線程同步

來源:互聯網
上載者:User

標籤:

    談到多線程編程,同步是一定要講的。給個例子:

#include <stdio.h>#include <stdlib.h>#include <pthread.h>int count = 0;#define N 100000void* fun(){    int i;    for (i = 0; i < N; ++i)    {        int tmp = count;        tmp++;        count = tmp;    }}int main(){    pthread_t tid1, tid2;    int ret1, ret2;    ret1 = pthread_create(&tid1, NULL, fun, NULL);    ret2 = pthread_create(&tid2, NULL, fun, NULL);    pthread_join(tid1, NULL);    pthread_join(tid2, NULL);    printf("count = %d\n", count);    return 0;}
View Code

    兩個線程同時對一個資料執行自增操作,結果是多少呢?

    可以看出,每次執行的結果都是不一樣的。而且,都不是我們所希望的200000。主要原因是程式裡的自增操作不是原子操作,兩個線程由於CPU的調度,會交錯執行。

接下來,我們通過互斥量來實現兩個線程的同步。

#include <stdio.h>#include <stdlib.h>#include <pthread.h>int count = 0;#define N 100000pthread_mutex_t mutex;void* fun(){    int i;    for (i = 0; i < N; ++i)    {        pthread_mutex_lock(&mutex);        int tmp = count;        tmp++;        count = tmp;        pthread_mutex_unlock(&mutex);    }}int main(){    pthread_mutex_init(&mutex, NULL);    pthread_t tid1, tid2;    int ret1, ret2;    ret1 = pthread_create(&tid1, NULL, fun, NULL);    ret2 = pthread_create(&tid2, NULL, fun, NULL);    pthread_join(tid1, NULL);    pthread_join(tid2, NULL);    printf("count = %d\n", count);    pthread_mutex_destroy(&mutex);    return 0;}
View Code

    在自增操作前後,通過成對的加鎖解鎖操作,使得自增操作成為一個原子操作,從而達到線程同步。

 

多線程同步

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.