hss
April 15, 2020, 5:50am
1
Hi
Very simple example here
1 let t = Thread.create (fun _ -> Printf.printf "hello\n") ();;
2 let _ = Unix.sleep 3;;
In line 1, I triggered thread and expect string of hello is printed to my terminal.
In line 2, I have a some trick to prevent terminating my program before starting the thread.
But, my output will be shown after 3 sec. why?
See this example in C/C++ style.
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
void *t_function(void *data)
{
printf("hello\n");
}
int main() {
pthread_t t;
pthread_create(&t, NULL, t_function, NULL);
sleep(3);
}
The string of hello is printed right after start the program and wait 3 sec. this is my expectation and works well.
So, How can I handle the mechanism of thread same as C/C++ ? the example of first program(Ocaml) is not my expectation.
Not running your code, but I notice you’re using Printf.printf. stdout is buffered. IIRC, so is stderr (sigh). So you need to “flush stdout” after the printf, in that thread.
hss
April 15, 2020, 8:37am
3
Oh thanks!
This code work, that print out before consumes 3 seconds.
let t = Thread.create (fun _ -> Printf.printf "hello\n"; flush stdout) ();;
let _ = Unix.sleep 3;;
But this code not works but I don’t know difference between above and below
let t = Thread.create (fun _ -> Printf.printf "hello\n") ();;
let _ = flush stdout; Unix.sleep 3;;
osener
April 15, 2020, 12:45pm
4
I suppose flush runs before the thread. Try
let t = Thread.create (fun _ -> Printf.printf "hello\n") ();;
let _ = print_endline "world"; Unix.sleep 3;;
You can use %!
in your format string for printf to flush the channel:
let t = Thread.create (fun _ -> Printf.printf "hello\n%!") ()
let () = Unix.sleep 3
1 Like