Skip to content

Instantly share code, notes, and snippets.

@ChinaXing
Created April 3, 2015 16:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ChinaXing/aaaf6cab0e32d6094667 to your computer and use it in GitHub Desktop.
Save ChinaXing/aaaf6cab0e32d6094667 to your computer and use it in GitHub Desktop.
message passing like channel use object monitor
package com.witown.probe.stream.storm;
import org.junit.Test;
import sun.awt.windows.ThemeReader;
/**
* Created by LambdaCat on 15/4/4.
*/
public class TestCSP {
private static Integer x = 0;
@Test
public void Test() {
Thread a = new Thread(new Runnable() {
public void run() {
synchronized (TestCSP.class) {
while (true) {
try {
Thread.sleep(1000);
TestCSP.class.wait();
System.out.println("X = " + x);
TestCSP.class.notify();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
});
Thread b = new Thread(new Runnable() {
public void run() {
synchronized (TestCSP.class) {
while (true) {
try {
x = x + 1;
TestCSP.class.notify();
Thread.sleep(500);
System.out.println("b alive after notify ..");
TestCSP.class.wait();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
});
a.start();
b.start();
try {
Thread.sleep(Integer.MAX_VALUE);
} catch (Exception e) {
}
}
}
@ChinaXing
Copy link
Author

两个通过临界区保护的进程。他们同时只能有一个处于锁的临界区,意味着,某一时刻,最多只有一个在运行,那么如果我们在临界区内进行协作,势必是如下情况:

  1. A 停止,B 运行
  2. B停止,A运行

即通过程序逻辑设置了一种协作顺序后,无论程序如何被调度,都不会影响这种顺序性。

比如:

  1. A停止,B在运行前被调度出去 =》 A,B 都暂停(因为即使A被调入运行,因为需要等待B的完成所以A也不会运行)

这里的锁,类似一种单核心的cpu。同时只有一个任务运行。

@ChinaXing
Copy link
Author

这里就是一种coroutine的情形?

  1. 可改造为运行在单个线程内部——wait 和 notify 改为函数调用或者跳转(没有堆栈)。
  2. 调度完全由程序本身来控制——协作,而非外部调度器。

协作方式的好处是减少不必要的切换,按需切换。

@ChinaXing
Copy link
Author

设计一种非分时的系统。系统线程、进程的切换完全由应用程序来控制,这样减少context switch,一定会高效。

@ChinaXing
Copy link
Author

逻辑调度器负责这种逻辑线程的切换,每当要暂停自己的时候,通知调度器,调度器挂起并记录,然后唤起等待条件的进程。

逻辑调度器在一个进程或者线程中运行,那么对于运行其的系统,完全是一个完成的线程,没有切换。

但是逻辑上讲,线程的内部完成了一种调度——这种调度是逻辑上的控制流的切换。

内涵于逻辑调度器及其被调度”线程“

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment