File: Threading.h

package info (click to toggle)
libexadrums 0.7.0-1.1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 652 kB
  • sloc: cpp: 6,970; ansic: 220; makefile: 160; sh: 12
file content (71 lines) | stat: -rw-r--r-- 1,446 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/*
 * Threading.h
 *
 *  Created on: 11 Feb 2018
 *      Author: jeremy
 */

#ifndef LIBEXADRUMS_UTIL_THREADING_H
#define LIBEXADRUMS_UTIL_THREADING_H

#include "Misc.h"

#include <algorithm>
#include <atomic>
#include <mutex>
#include <thread>

namespace Util
{


	static constexpr size_t minNbThreads = 3; // Minimum number of threads available to enable threads priority.

	/**
	 * @brief Gives a relative priority to a thread, only if more than minNbThreads threads are available.
	 * @param threadHandle Native handle of the thread object.
	 * @param p Priority in percent: 0 = min, 100 = max.
	 * @param schedType Type of scheduler.
	 */
	template <typename T>
	static void SetThreadPriority(const T& threadHandle, int p, int schedType = SCHED_FIFO)
	{

		if(std::thread::hardware_concurrency() >= minNbThreads)
		{
			p = Util::clamp(p, 0, 100);

			auto maxPriority{sched_get_priority_max(SCHED_FIFO)};
			size_t priority = static_cast<size_t>((p * maxPriority) / 100);

			sched_param sch_params;
			sch_params.sched_priority = priority;

			pthread_setschedparam(threadHandle, schedType, &sch_params);
		}
	}

	class SpinLock
	{

	public:

	    void lock()
	    {
	        while(locked.test_and_set(std::memory_order_acquire)) { ; }
	    }

	    void unlock()
	    {
	        locked.clear(std::memory_order_release);
	    }

	private:

	    std::atomic_flag locked = ATOMIC_FLAG_INIT;
	};

}


#endif /* LIBEXADRUMS_UTIL_THREADING_H */