點擊(此處)折疊或打開
克什克騰ssl適用于網站、小程序/APP、API接口等需要進行數據傳輸應用場景,ssl證書未來市場廣闊!成為創新互聯公司的ssl證書銷售渠道,可以享受市場價格4-6折優惠!如果有意向歡迎電話聯系或者加微信:18982081108(備注:SSL證書合作)期待與您的合作!
-
{
-
int b = 0;
-
b = a;
-
a = b+1;
-
return *this;
-
}
-
就是臨界區代碼
后面將對他們進行描述,這里我們簡單實用靜態互斥鎖進行解決這個問題。
-
//原子操作 加鎖
-
pthread_mutex_lock(&mtx);
-
++test;
-
pthread_mutex_unlock(&mtx);
-
//原子操作 解鎖
-
cout<<pthread_self() <<":";
-
test.prit()
實際上我們就是保護了操作符重載的testc& operator++()
臨界區的選擇應該盡量小,避免對多線程的并發性產生較大的性能影響
具體代碼如下:
-
/*************************************************************************
-
> File Name: error.cpp
-
> Author: gaopeng QQ:22389860 all right reserved
-
> Mail: gaopp_200217@163.com
-
> Created Time: Mon 15 May 2017 12:01:33 AM CST
-
************************************************************************/
-
-
#include<iostream>
-
#include <pthread.h>
-
#include <string.h>
-
#define MAXOUT 1000000
-
using namespace std;
-
-
static pthread_mutex_t mtx=PTHREAD_MUTEX_INITIALIZER;
-
-
-
class testc
-
{
-
private:
-
int a;
-
public:
-
testc()
-
{
-
a = 1;
-
}
-
testc& operator++()
-
{
-
int b = 0;
-
b = a;
-
a = b+1;
-
return *this;
-
-
}
-
void prit()
-
{
-
cout<<a<<endl;
-
}
-
};
-
-
-
testc test = test;
-
-
-
void* testp(void* arg)
-
{
-
int i = MAXOUT;
-
-
while(i--)
-
{
-
//原子操作 加鎖
-
pthread_mutex_lock(&mtx);
-
++test;
-
pthread_mutex_unlock(&mtx);
-
//原子操作 解鎖
-
cout<<pthread_self() <<":";
-
test.prit();
-
}
-
}
-
-
-
-
-
int main(void)
-
{
-
pthread_t tid[3];
-
int er;
-
int i = 0;
-
-
while(i<3)
-
{
-
-
if ((er = pthread_create(tid+i,NULL,testp,NULL) )!=0 )
-
{
-
strerror(er);
-
return -1;
-
}
-
i++;
-
}
-
-
i = 0;
-
-
while(i<3)
-
{
-
pthread_join(*(tid+i),NULL);
-
i++;
-
}
-
cout<<"last numer: ";
-
test.prit();
-
}
注意:一個簡單類型的i++也不一定是一個原子操作,所以在涉及到并發修改共享變量的時候一定要使用
線程同步手段。
作者微信:
當前文章:一、(LINUX線程同步)引入
標題網址:http://vcdvsql.cn/article28/gjiecp.html
成都網站建設公司_創新互聯,為您提供靜態網站、外貿網站建設、網站導航、網站策劃、建站公司、服務器托管
廣告
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源:
創新互聯