multithreading - Semaphores & threads - what is the point? -


i've been reading semaphores , came across article:

www.csc.villanova.edu/~mdamian/threads/posixsem.html

so, page states if there 2 threads accessing same data, things can ugly. solution allow 1 thread access data @ same time.

this clear , understand solution, why need threads this? point? if threads blocked 1 can execute, why use them @ all? there no advantage. (or maybe dumb example; in such case please point me sensible one)

thanks in advance.

consider this:

void update_shared_variable() {     sem_wait( &g_shared_variable_mutex );      g_shared_variable++;      sem_post( &g_shared_variable_mutex ); }  void thread1() {      do_thing_1a();     do_thing_1b();     do_thing_1c();      update_shared_variable();   // may block }  void thread2() {      do_thing_2a();     do_thing_2b();     do_thing_2c();      update_shared_variable();   // may block } 

note of do_thing_xx functions still happen simultaneously. semaphore comes play when threads need modify shared (global) state or use shared resource. thread block if thread trying access shared thing @ same time.

now, if only thing threads doing working 1 single shared variable/resource, correct - there no point in having threads @ (it less efficient 1 thread, due context switching.)


Comments

Popular posts from this blog

javascript - Count length of each class -

What design pattern is this code in Javascript? -

hadoop - Restrict secondarynamenode to be installed and run on any other node in the cluster -