#include "pthread.h"
#include <stdlib.h>
#include <iostream>
#include <stdint.h>
#include <assert.h>
#include <string>
#include <vector>
#include "aa_lock.h"
static const int gMaxCountTime = 10000;
static const int gTextThreadNum = 100;
static pthread_t ts[gTextThreadNum];
static int64_t gCount = 0;
static std::vector<int> gCountArray;
void* StartPthread(void* data)
{
for (int i = 0; i < gMaxCountTime; ++i)
{
// 去掉锁的话,下边的assert随时crash.
// 可对对象加锁,类似objc或Java的同步关键字sychronized
AALock::GLock(&gCount);
++gCount;
AALock::GUnLock(&gCount);
// 去掉锁,push_back随时崩溃,因为vector并不是线程安全的.
AALock::GLock(&gCountArray);
gCountArray.push_back(i);
AALock::GUnLock(&gCountArray);
}
return NULL;
}
void TestAALock()
{
for (int i = 0; i < gTextThreadNum; ++i)
{
pthread_create(&ts[i],NULL,StartPthread,NULL);
}
for (int i = 0; i < gTextThreadNum; ++i)
{
pthread_join(ts[i],NULL);
}
std::cout << "gCount: " << gCount << std::endl;
assert(gCount == gMaxCountTime*gTextThreadNum);
std::cout << "gCountArray size: " << gCountArray.size() << std::endl;
assert(gCount == gCountArray.size());
}
int main(int argc, char const *argv[])
{
for (int i = 0; i < 10; ++i)
{
TestAALock();
gCount = 0;
gCountArray.clear();
}
return 0;
}
没有合适的资源?快使用搜索试试~ 我知道了~
[并发并行]_[初级]_[C++实现sychronized方式的对象锁]
共9个文件
h:4个
cpp:2个
dll:1个
5星 · 超过95%的资源 需积分: 1 19 下载量 112 浏览量
2015-12-05
00:57:38
上传
评论
收藏 322KB ZIP 举报
温馨提示
参考: http://blog.csdn.net/infoworld/article/details/50182241
资源推荐
资源详情
资源评论
收起资源包目录
test.zip (9个子文件)
test
aa_lock.h 228B
test.cpp 1KB
include
semaphore.h 4KB
pthread.h 41KB
sched.h 5KB
test.exe 1018KB
pthreadGC2.dll 73KB
build.bat 59B
aa_lock.cpp 1KB
共 9 条
- 1
资源评论
- xy875371112017-01-19最近也遇到了多线程安全问题,非常感谢楼主分享代码,特别是下载不需要积分。非常感谢。
- hunter_adiwang2017-03-27感谢分享,学些一下
Peter(阿斯拉达)
- 粉丝: 747
- 资源: 60
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功