简体   繁体   English

如何在不使用任何同步方法的情况下同步线程?

[英]How to synchronise threads without using any synchronisation methods?

I was asked in an interview that it is required to print numbers 1 to 3 in a sequential order by 3 threads without using any synchronisation techniques.我在一次采访中被问到,需要在不使用任何同步技术的情况下,由 3 个线程按顺序打印数字 1 到 3。

I think that we can access the thread id to find out which thread it is and keep a flag associated with this thread in a structure which can be set to true this thread in currently accessing the data.我认为我们可以访问线程 id 以找出它是哪个线程,并将与该线程关联的标志保留在一个结构中,该结构可以在当前访问数据时将此线程设置为 true。

Interviewer laughed at this idea.面试官嘲笑这个想法。 So obviously it is wrong.所以显然是错误的。

What can be the way to achieve this task?完成这项任务的方法是什么?

You use a single-core scheduler with lock-free ICPP scheduling strategy .您使用具有无锁ICPP 调度策略的单核调度程序。 This is not covered by the C++ stdlib, but POSIX has an API for it.这不在 C++ stdlib 中,但 POSIX 有一个 API。

Since you are on a single core, only one thread runs at any time, and ICPP guarantees that it will never be preempted while holding a resource by another thread that wants to access that same resource.由于您在单核上,任何时候都只有一个线程在运行,并且 ICPP 保证它永远不会在持有资源时被另一个想要访问同一资源的线程抢占。 Therefore, you don't need thread synchronization.因此,您不需要线程同步。

Create thread A
Thread A prints '1'
Thread A creates thread B and exits
Thread B prints '2'
Thread B creates thread C and exits
Thread C prints '3' and
exits

No explicit synchro required, prints 1,2,3 in order using three threads, is a totally pointless exercise.不需要显式同步,使用三个线程按顺序打印 1,2,3,是完全没有意义的练习。

My first thought, but context switch might happen between std::count and ++i .我的第一个想法,但上下文切换可能发生在std::count++i

class Solution{
  private:
     atomic<int> i(0);
  public:

// func 1 2 3 are identical.
     void func1(){
         std::cout<< ++i;
     }

     void func2(){
         std::cout<< ++i;
     }

     void func3(){
         std::cout<< ++i;
     }

}

Second thought, using atomic with spin lock, so execution order should be fixed.第二个想法,使用带有自旋锁的原子,所以执行顺序应该是固定的。

class Solution{
  private:
     atomic<int> i(1);
  public:
     void func1(){
         std::cout<< i;
         ++i;
     }

     void func2(){
         while( i != 2);
         std::cout<< i;
         ++i;
     }

     void func3(){
         while( i != 3);
         std::cout<< i;
         ++i;
     }

}

for fun:为了娱乐:

Emit them by time?按时间发射它们?

for example例如

print 1 at 00:01在 00:01 打印 1
print 2 at 00:02在 00:02 打印 2
print 3 at 00:03在 00:03 打印 3

If you set the time interval big enough that the chance they run out-of-order is lower than a bit flip in the system, then you are good.如果您将时间间隔设置得足够大,以至于它们无序运行的机会低于系统中的位翻转,那么您就很好。

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

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