From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: X-Original-To: caml-list@sympa.inria.fr Delivered-To: caml-list@sympa.inria.fr Received: from mail2-relais-roc.national.inria.fr (mail2-relais-roc.national.inria.fr [192.134.164.83]) by sympa.inria.fr (Postfix) with ESMTPS id C78BF7EE4B for ; Mon, 30 Sep 2013 11:18:04 +0200 (CEST) X-IronPort-AV: E=Sophos;i="4.90,1007,1371074400"; d="scan'208";a="34870781" Received: from estephe.inria.fr (HELO [128.93.11.95]) ([128.93.11.95]) by mail2-relais-roc.national.inria.fr with ESMTP; 30 Sep 2013 11:18:03 +0200 Message-ID: <524941CC.1080906@inria.fr> Date: Mon, 30 Sep 2013 11:18:04 +0200 From: Xavier Leroy User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:17.0) Gecko/20130623 Thunderbird/17.0.7 MIME-Version: 1.0 To: caml-list@inria.fr References: In-Reply-To: X-Enigmail-Version: undefined Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit Subject: Re: [Caml-list] Thread behaviour On 2013-09-27 12:10, Tom Ridge wrote: > I have a little program which creates a thread, and then sits in a loop: > [...] > When I run the program I get the output: > > 1 > 2 > > and the program then sits in the loop. On my machine (OCaml 4.01.0, Ubuntu 12.04 LTS), I sometimes see what you see, and sometimes I see the expected output: 1 2 3 hello 4 It all depends on the whim of the OS scheduler. OCaml has no control over it. And you shoudn't expect any kind of fairness from the OS scheduler, esp. Linux's, which gladly jettisons any pretense of fairness in the hope of getting better throughput. > Would it be fair to say that OCaml does not currently support > pre-emptively scheduled threads? This would be inexact. OCaml's threads yield the runtime lock, giving other threads a chance to grab it and run, in the following cases: 1- when performing an I/O operation that may block or take a long time ("flush" in your example) 2- when the program calls Thread.yield (duh) 3- when a timer interrupt is detected at certain program points: 3a- for native-code compilation: minor heap allocations 3b- for bytecode compilation: function calls + beginning of every loop iteration. What happens after yielding is the business of the OS scheduler, though. > I should be using a message passing interface written in some other > language, with bindings to OCaml. You have plenty of options depending on what you really need in the end: - For parallelism (getting speedups from a sequential program), consider the Parmap and Functory libraries. - For concurrency with message passing and possible distribution, consider JoCaml. - If you want to write your own message-passing library and want to control every bit of the scheduling, LWT (lightweight cooperative threads) is probably best. - You can also use system threads, but only if you give up on any hope of fairness and write in a style that is resistant against whatever awful scheduling the OS will do for you. Hope this helps, - Xavier Leroy