UNIX threads - about sleep and how to make a thread work for certain time?

In UNIX, if a thread calls sleep function, will the entire process not do any work for that time or only the sleep calling thread will not do any work for that time?

In a multi-threaded program, I want a thread to work for certain amount of time, how to achieve this?

Answers


man sleep says:

The sleep() function suspends execution of the calling thread until either seconds seconds have elapsed
or a signal is delivered to the thread and its action is to invoke a signal-catching function or to
terminate the thread or process.  System activity may lengthen the sleep by an indeterminate amount.

This function is implemented using nanosleep(2) by pausing for seconds seconds or until a signal
occurs.  Consequently, in this implementation, sleeping has no effect on the state of process timers,
and there is no special handling for SIGALRM.

so "only the calling thread".

As for your second question: It's mostly beyond your control and most people should rethink their design and leave that to the OS -- your OS controls your threads' execution. You can use conditions and signals to coordinate threads' actions to some extent. It's typically better/easier to use fewer threads and manage tasks, rather than threads directly. Even if you want to time it, there's a lot of work in trying to figure out at runtime how much time your threads are being given.


Need Your Help

Incrementing values in 2d array?

python arrays list

I'm attempting to increment the values in a 2d array for a game I'm making, but I'm getting the same value in each array instead. This is the code:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.