如何在不使用任何同步方法的情况下同步线程? [英] How to synchronise threads without using any synchronisation methods?

查看:36
本文介绍了如何在不使用任何同步方法的情况下同步线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一次采访中被问到,需要使用 3 个线程按顺序打印数字 1 到 3,而不使用任何同步技术.

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.

我认为我们可以访问线程 id 以找出它是哪个线程,并将与该线程关联的标志保留在一个结构中,该结构可以在当前访问数据时将此线程设置为 true.

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.

面试官嘲笑这个想法.所以很明显这是错误的.

Interviewer laughed at this idea. So obviously it is wrong.

完成这项任务的方法是什么?

What can be the way to achieve this task?

推荐答案

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

不需要显式同步,使用三个线程按顺序打印 1,2,3,完全没有意义.

No explicit synchro required, prints 1,2,3 in order using three threads, is a totally pointless exercise.

这篇关于如何在不使用任何同步方法的情况下同步线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆