pthread sleep linux

前端 未结 5 2066
孤独总比滥情好
孤独总比滥情好 2020-12-09 02:55

I am creating a program with multiple threads using pthreads.

Is sleep() causing the process (all the threads) to stop executing or just the thread whe

5条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-09 03:31

    In practice, there are few cases where you just want to sleep for a small delay (milliseconds). For Linux, read time(7), and see also this answer. For a delay of more than a second, see sleep(3), for a small delay, see nanosleep(2). (A counter example might be a RasPerryPi running some embedded Linux and driving a robot; in such case you might indeed read from some hardware device every tenth of seconds). Of course what is sleeping is just a single kernel-scheduled task (so a process or thread).

    It is likely that you want to code some event loop. In such a case, you probably want something like poll(2) or select(2), or you want to use condition variables (read a Pthread tutorial about pthread_cond_init etc...) associated with mutexes.

    Threads are expensive resources (since each needs a call stack, often of a megabyte at least). You should prefer having one or a few event loops instead of having thousands of threads.

    If you are coding for Linux, read also Advanced Linux Programming and syscalls(2) and pthreads(7).

提交回复
热议问题