pthreads: thread starvation caused by quick re-locking

前端 未结 5 625
误落风尘
误落风尘 2020-11-28 13:01

I have a two threads, one which works in a tight loop, and the other which occasionally needs to perform a synchronization with the first:

// thread 1
while(         


        
5条回答
  •  一个人的身影
    2020-11-28 13:22

    pthread offers a notion of thread priority in its API. When two threads are competing over a mutex, the scheduling policy determines which one will get it. The function pthread_attr_setschedpolicy lets you set that, and pthread_attr_getschedpolicy permits retrieving the information.

    Now the bad news:

    • When only two threads are locking / unlocking a mutex, I can’t see any sort of competition, the first who runs the atomic instruction takes it, the other blocks. I am not sure whether this attribute applies here.
    • The function can take different parameters (SCHED_FIFO, SCHED_RR, SCHED_OTHER and SCHED_SPORADIC), but in this question, it has been answered that only SCHED_OTHER was supported on linux)

    So I would give it a shot if I were you, but not expect too much. pthread_yield seems more promising to me. More information available here.

提交回复
热议问题