该程序将创建多个线程,其中每个线程使用for循环将共享变量递增10000,该循环在每次迭代中将共享变量递增1。互斥锁和自旋锁(忙等待)版本都是必需的。据我所知,互斥锁的工作速度应该比自旋锁快。但是我的实现给了我一个相反的答案...
这是互斥锁版本中每个线程的实现:
void *incr(void *tid)
{
int i;
for(i = 0; i < 10000; i++)
{
pthread_mutex_lock(&the_mutex); //Grab the lock
sharedVar++; //Increment the shared variable
pthread_mutex_unlock(&the_mutex); //Release the lock
}
pthread_exit(0);
}这是在自旋锁版本中的实现:
void *incr(void *tid)
{
int i;
for(i = 0; i < 10000; i++)
{
enter_region((int)tid); //Grab the lock
sharedVar++; //Increment the shared variable
leave_region((int)tid); //Release the lock
}
pthread_exit(0);
}
void enter_region(int tid)
{
interested[tid] = true; //Show this thread is interested
turn = tid; //Set flag
while(turn == tid && other_interested(tid)); //Busy waiting
}
bool other_interested(int tid) //interested[] is initialized to all false
{
int i;
for(i = 0; i < tNumber; i++)
if(i != tid)
if(interested[i] == true) //There are other threads that are interested
return true;
return false;
}
void leave_region(int tid)
{
interested[tid] = false; //Depart from critical region
}我还对创建和运行线程的过程进行了数百次迭代,以确保可以区分执行时间。例如,如果tNumber是4,并且我将程序迭代了1000次,互斥将花费2.22秒,而自旋锁定将花费1.35秒。这种差异随着tNumber的增加而增大。为什么会发生这种情况?我的代码是错的吗?
发布于 2012-02-27 03:45:29
enter_region和leave_region之间的代码不受保护。
您可以通过使它变得更加复杂来证明这一点,以确保它会自己出错。
创建一个长度为10000的布尔(检查)数组,设置为false。在enter和leave之间设置代码:
if (check[sharedVar]) cout << "ERROR" << endl;
else check[sharedVar++] = true;https://stackoverflow.com/questions/9456432
复制相似问题