Skip to content

Instantly share code, notes, and snippets.

@shotamatsuda
Last active August 29, 2015 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shotamatsuda/e11ed41ee2978fa5a2f1 to your computer and use it in GitHub Desktop.
Save shotamatsuda/e11ed41ee2978fa5a2f1 to your computer and use it in GitHub Desktop.
Name the worker threads of boost’s threadpool
#include <cassert>
#include <condition_variable>
#include <cstddef>
#include <mutex>
#include <string>
#include "boost/threadpool.hpp"
void NameThisThread(const std::string& name);
template <
typename Task,
template <typename> class SchedulingPolicy,
template <typename> class SizePolicy,
template <typename> class SizePolicyController,
template <typename> class ShutdownPolicy>
inline void NameThreadpoolWorkers(
const std::string& name,
boost::threadpool::thread_pool<
Task, SchedulingPolicy, SizePolicy,
SizePolicyController, ShutdownPolicy> *pool) {
assert(pool);
pool->wait();
std::mutex mutex;
std::condition_variable condition;
bool predicate = false;
std::unique_lock<std::mutex> lock(mutex);
for (std::size_t i = 0; i < pool->size(); ++i) {
pool->schedule([&name, &mutex, &condition, &predicate]() {
std::unique_lock<std::mutex> lock(mutex);
while (!predicate) {
condition.wait(lock);
}
NameThisThread(name);
});
}
predicate = true;
condition.notify_all();
lock.unlock();
pool->wait();
}
#include "thread_name.h"
#include <string>
#import <Cocoa/Cocoa.h>
void NameThisThread(const std::string& name) {
NSString *string;
if (string.empty()) {
string = [NSString string];
} else {
string = [NSString stringWithUTF8String:string.c_str()];
}
[[NSThread currentThread] setName:string];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment