简体   繁体   English

Posix线程-并行线程

[英]Posix Threads - Threads in Parallel

int total = 200; // total is a global variable

void process()
{
    int local;
    for( int i = 0 ; i< 100 ; i++ ) 
    {
         local = total;
         local--;
         total = local;
    }
}

If 2 threads invoke process() in parallel, what will be the maximum & minimum value of total after both threads finish processing? 如果2个线程调用process()平行,这将是的最大和最小值之后两个线程完成处理?

i think the minimum value will be 0 but im not sure. 我认为最小值将为0,但我不确定。 maximum value ?? 最大值?? 199 ? 199吗?

In C11 this is defined as "undefined behavior," which means that it gives no guarantees about it. 在C11中,这被定义为“未定义的行为”,这意味着它不提供任何保证。

This is more or less true of C99 also, although C99 was not written with concurrency in mind. 尽管在编写C99时并没有考虑到并发性,但C99也是如此。 Each thread is ignorant of the other. 每个线程都不知道对方。

Each thread will look at the global variable 'total' 100 times. 每个线程将查看全局变量“总计” 100次。

However, each thread gets its own local copy, decrements that, and writes it back to the global variable, total. 但是,每个线程都有自己的本地副本,将其递减,然后将其写回到全局变量total中。

However, the thread may take the global variable 'total' and keep a temporary copy, without writing it back until the function ends. 但是,线程可能会使用全局变量“ total”并保留一个临时副本,直到函数结束之前才将其写回。 In this case the lower bound might be 100. 在这种情况下,下限可能是100。

If they don't keep local copies, total may go down by no more than 1, as they both grab total in synchrony, decrement their local copy, and write back. 如果他们不保留本地副本,则总数可能会减少不超过1,因为它们都同步获取总数,减少其本地副本并写回。

Without some way of synchronizing the threads, so that one "grabs" total, modifies it, then "releases" it while the other waits, there's no guarentee it'll reach 0. 如果没有某种同步线程的方法,那么一个“抓取”总数将被修改,然后“释放”,而另一个则将等待,因此没有保证它将达到0。

Mutexes, semaphores, etc. are ways to syncrhonize access across threads. 互斥体,信号量等是同步跨线程访问的方法。

Pseudo-code: 伪代码:

process() {
  for (loop) {
    grab_mutex(total);  // Will wait till total is free
    total--;
    release_mutex(total);
  }
}

However, the lower bound is definitely 0; 但是,下界一定是0; there are no more than 200 opportunities for a decrement. 递减的机会不超过200。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM