Phix: Understanding Multithreading

new topic     » topic index » view thread      » older message » newer message

Hey, Pete! Can you fix this simple demo for me? I'm just trying to get a better grip on multithreading.

It actually works for a few seconds, doing what it's supposed to do, but then it crashes.

I think I got it! I was using a plain ?x, and I think maybe that's what was crashing it.

If you run the below code without the enter_cs()/leave_cs(), it crashes eventually. With them there, it works.

Pete, let me know if I'm on the right track here!

Thank you!

-- simple app to show multi-threading in Phix 
-- start 4 threads 
-- each thread will wait X seconds and then print its output 
 
atom cs = init_cs() 
bool terminate = false 
 
constant ESC = #1B 
 
procedure counter(integer x) 
atom nowTime 
atom endTime = time() + x 
    while not terminate do 
        nowTime = time() 
        if nowTime >= endTime then 
            endTime = nowTime + x 
            enter_cs(cs) --<-- this is required to not crash 
            ?x 
            leave_cs(cs) --<-- this is required to not crash 
        end if 
    end while 
    exit_thread(0) 
end procedure 
atom rid = routine_id("counter") 
 
procedure main() 
sequence threads = { 
        create_thread(rid,{1}), 
        create_thread(rid,{2}), 
        create_thread(rid,{4}), 
        create_thread(rid,{8}) 
    } 
 
    while not find(get_key(),{ESC,'q','Q'}) do 
    end while 
    terminate = true 
    wait_thread(threads) 
    delete_cs(cs) 
 
    puts(1,"done") 
    if getc(0) then end if 
 
end procedure 
 
main() 
new topic     » topic index » view thread      » older message » newer message

Search



Quick Links

User menu

Not signed in.

Misc Menu