简体   繁体   中英

What is a Spinning Thread?

I have stumbled upon the term spinning, referring to a thread while reading this (ROS)

What is the general concept behind spinning a thread?

My intuition would say that a spinning thread is a thread that keeps executing in a multithreading process with a certain frequency, somewhat related to the concept of polling (ie keep checking some condition with a certain frequency) but I am not sure at all about it.

Could you give some explanation? The more general the better.

There are a couple of separate concepts here.

In terms of ROS (the link you reference), ros::spin() runs the ROS callback invoker, so that pending events are delivered to your program callbacks via a thread belonging to your program. This sort of call typically does not return; it will wait for new events to be ready, and invoke appropriate callbacks when they occur.

But you also refer to "spinning a thread."

This is a separate topic. It generally relates to a low level programming pattern whereby a thread will repeatedly check for some condition being met without being suspended.

A common way to wait for some condition to be met is to just wait on a conditional variable. In this example, the thread will be suspended by the kernel until some other thread calls notify on the condition variable. Upon the notify, the kernel will resume the thread, and the condition will evaluate to true, allowing the thread to continue.

std::mutex m;
std::condition_variable cv;
bool ready = false;
std::unique_lock<std::mutex> lk(m);
cv.wait(lk, []{ return ready; });  /* thread suspended */

Alternatively a spinning approach would repeatedly check some condition, without going to sleep. Caution: this results in high CPU, and there are subtle caveats to implementing correctly).

Here is an example of a simple spinlock (although note that spinning threads can be used for other purposes than spinlocks). In the below code, notice that the while loop repeatedly calls test_and_set ... which is just an attempt to set the flag to true; that's the spin part.

// spin until true
std::atomic_flag lock = ATOMIC_FLAG_INIT;

while (lock.test_and_set(std::memory_order_acquire));  // acquire lock
/* got the flag .. do work */
lock.clear(std::memory_order_release);               // release lock

spin like while loop without sleeping, your task consumes cpu resource constantly until the conditions is satisfied.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM