linux thread synchronization

后端 未结 5 918
北海茫月
北海茫月 2021-02-06 14:52

I am new to linux and linux threads. I have spent some time googling to try to understand the differences between all the functions available for thread synchronization. I sti

相关标签:
5条回答
  • 2021-02-06 15:10

    regarding question # 8 Is there a better way than using a condition to sleep a thread when there is no work? yes i think that the best aproach instead of using sleep is using function like sem_post() and sem_wait of "semaphore.h"

    regards

    0 讨论(0)
  • 2021-02-06 15:24

    Application code should probably use posix thread functions. I assume you have man pages so type

    man pthread_mutex_init
    man pthread_rwlock_init
    man pthread_spin_init
    

    Read up on them and the functions that operate on them to figure out what you need.

    If you're doing kernel mode programming then it's a different story. You'll need to have a feel for what you are doing, how long it takes, and what context it gets called in to have any idea what you need to use.

    0 讨论(0)
  • 2021-02-06 15:25

    in addtion you should check the nexts books

    • Pthreads Programming: A POSIX Standard for Better Multiprocessing

    and

    • Programming with POSIX(R) Threads
    0 讨论(0)
  • 2021-02-06 15:28

    A note on futexes - they are more descriptively called fast userspace mutexes. With a futex, the kernel is involved only when arbitration is required, which is what provides the speed up and savings.

    Implementing a futex can be extremely tricky (PDF), debugging them can lead to madness. Unless you really, really, really need the speed, its usually best to use the pthread mutex implementation.

    Synchronization is never exactly easy, but trying to implement your own in userspace makes it inordinately difficult.

    0 讨论(0)
  • 2021-02-06 15:37

    Thanks to all who answered. We resorted to using gcc atomic operations to synchronize all of our threads. The atomic ops were about 2x slower than setting a value without synchronization, but magnitudes faster than locking a mutex, changeing the value, and then unlocking the mutex (this becomes super slow when you start having threads bang into the locks...) We only use pthread_create, attr, cancel, and kill. We use pthread_kill to signal threads to wake up that we put to sleep. This method is 40x faster than cond_wait. So basicly....use pthreads_mutexes if you have time to waste.

    0 讨论(0)
提交回复
热议问题