互斥N个异步线程 [英] Mutual Exclusion for N Asynchronous Threads

查看:120
本文介绍了互斥N个异步线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个异步应用,这意味着在任何时候可以有N个事件。是否存在已知的算法做互斥的N个线程,没有硬编码每个线程有一个ID?

I've got an asynchronous application, meaning that at any given time there can be N events. Is there a known algorithm for doing mutual exclusion for N threads, without hardcoding each thread to have an ID?

推荐答案

我不认为使用Javascript本身具有的对象锁定 - 因为JavaScript基本上是单线程的。你也许可以找到运行的JavaScript code的多个线程库或实现 - 但他们都在同一个可变空间中运行?他们将需要以某种方式彼此进行通信。

I don't think Javascript per se has object locking - because Javascript is basically single-threaded. You might be able to find a library or implementation that runs several threads of Javascript code - but are they all running in the same variable-space? They will need to communicate with each other somehow.

假设您的多个线程可以共享一个静态互斥变量不知何故,并且只要您假设 ++ 被认为是该做的穿线系统,这个怎么样?

Assuming your multiple threads can share a static mutex variable somehow, and insofar as you assume '++' is considered an atomic operation for the system that is doing your threading, how about this?

int mutex = 0;
mutuallyExclusiveOperation(){
  succeed=false;
  while(!succeed){
    while(mutex>0){ sleep();  }
    m=mutex++;   //"Simultaneously" read and increment
    if(m>0)mutex--;
    else{
      doMutuallyExclusiveThing();
      succeed=true;
      mutex--;
    }
 }
}

这篇关于互斥N个异步线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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