- 论坛徽章:
- 0
|
class Inc:public Thread
{
public:
Inc(int id, int *inc):Thread(id), value(inc){};
private:
int *value;
void run()
{
this->lock.enterCriticSection();
for(int i = 0; i < 30; ++i)
{
std::cout << (*value)++ << " thread_id " << this->id << std::endl;
int s;
for(int j = 0; j < 40000; ++j) //为了让cpu执行到时间片完而让与给其他线程
s++;
}
this->lock.leaveCriticSection();
}
};
Thread类有一个lock对象,lock对象有一个pthread_mutex_t对象。
enterCriticSection函数是给pthread_mutex_lock的包裹函数,leaveCriticSection是pthread_mutex_unlock的包裹函数。
value是从主线程传进来的一块内存,我在主线程创建了两个Inc线程,用来对value自加。如果不加锁,会出现交叉情况,我现在加锁是为了让一个线程先执行完,另一个线程接着执行不会有交叉,但是结果跟我不用锁的结果差不多,请问这样用为什么不对呢?
[ 本帖最后由 cheney_lang 于 2008-1-16 13:00 编辑 ] |
|