Mutex

A mutex is an object used for controlling access in a multi-threaded system.

#include <mutex>
std::mutex mtx; /* global */

void thread_test(Sound* s) {
	while(1) {
		usleep(200000); /* 0.2sec */
		mtx.lock();
		s->loop_count = s->asound_read(); /* write pointer goes forward */
		mtx.unlock();
	}
}

bool MyDrawingAreaS::on_draw(const Cairo::RefPtr<Cairo::Context> &cr) {
	if(s->loop_count) {
		while(s->signal_end - s->signal_start >= nfft*channels) {
			mtx.lock();
			s->asound_fftcopy(); /* write pointer sometimes goes back */
			mtx.unlock();
//
}
% ag locked log.txt | tail
58033:AAA locked in thread_test();
58037:BBB locked in on_draw();
58038:BBB locked in on_draw();
58039:BBB locked in on_draw();
58040:BBB locked in on_draw();
58041:BBB locked in on_draw();
58042:BBB locked in on_draw();
58043:BBB locked in on_draw();
58044:AAA locked in thread_test();
58046:BBB locked in on_draw();
58047:BBB locked in on_draw();

% ag AAA | wc; ag BBB | wc                          
   4284   17136  183477
  40219  160876 1561654

The lines AAA and BBB should appear 5 (=1/0.2) times per second, and 46.9 (=48000/1024) times per second, respectively. Note that 40219/4284 (= 9.39) is close to 46.9/5 (=9.37).

Leave a Reply

Your email address will not be published. Required fields are marked *