ThreadUtils.cpp 9.11 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//###########################################################################
// This file is part of LImA, a Library for Image Acquisition
//
// Copyright (C) : 2009-2011
// European Synchrotron Radiation Facility
// BP 220, Grenoble 38043
// FRANCE
//
// This is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3 of the License, or
// (at your option) any later version.
//
// This software is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, see <http://www.gnu.org/licenses/>.
//###########################################################################
22
23
#include "lima/ThreadUtils.h"
#include "lima/Exceptions.h"
ahoms's avatar
ahoms committed
24
#include <errno.h>
25
#include <iomanip>
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
26
#ifdef __unix
27
#include <sys/time.h>
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
28
29
30
#else
#include <time_compat.h>
#endif
31
#include <unistd.h>
32
33

#if !defined(_WIN32)
34
#include <sys/syscall.h>
35
#endif
ahoms's avatar
ahoms committed
36
37
38

using namespace lima;

39
40
41
42
43
44
45
46
47
48
inline void check_error(int ret, const char *desc)
{
	if (ret == 0)
		return;
	std::ostringstream os;
	os << desc << ": " << strerror(ret) << " (" << ret << ")";
	throw LIMA_COM_EXC(Error, os.str());
}


ahoms's avatar
ahoms committed
49
50
MutexAttr::MutexAttr(Type type)
{
51
52
	int ret = pthread_mutexattr_init(&m_mutex_attr);
	check_error(ret, "Error initializing mutex attr");
ahoms's avatar
ahoms committed
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88

	try {
		setType(type);
	} catch (...) {
		destroy();
		throw;
	}
}

MutexAttr::MutexAttr(const MutexAttr& mutex_attr)
	: m_mutex_attr(mutex_attr.m_mutex_attr)
{
}

MutexAttr::~MutexAttr()
{
	destroy();
}

void MutexAttr::setType(Type type)
{
	int kind;
	switch (type) {
	case Normal: 
		kind = PTHREAD_MUTEX_NORMAL;
		break;
	case Recursive:
		kind = PTHREAD_MUTEX_RECURSIVE;
		break;
	case ErrorCheck:
		kind = PTHREAD_MUTEX_ERRORCHECK;
		break;
	default:
		throw LIMA_COM_EXC(InvalidValue, "Invalid MutexAttr type");
	}

89
90
	int ret = pthread_mutexattr_settype(&m_mutex_attr, kind);
	check_error(ret, "Error setting mutex attr");
ahoms's avatar
ahoms committed
91
92
93
94
95
}

MutexAttr::Type MutexAttr::getType() const
{
	int kind;
96
97
	int ret = pthread_mutexattr_gettype(&m_mutex_attr, &kind);
	check_error(ret, "Error getting mutex attr");
ahoms's avatar
ahoms committed
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132

	switch (kind) {
	case PTHREAD_MUTEX_NORMAL:
		return Normal;
	case PTHREAD_MUTEX_RECURSIVE:
		return Recursive;
	case PTHREAD_MUTEX_ERRORCHECK:
		return ErrorCheck;
	default:
		throw LIMA_COM_EXC(Error, "Invalid mutex attr kind");
	}
}

MutexAttr& MutexAttr::operator =(Type type)
{
	setType(type);
	return *this;
}

MutexAttr& MutexAttr::operator =(const MutexAttr& mutex_attr)
{
	m_mutex_attr = mutex_attr.m_mutex_attr;
	return *this;
}

void MutexAttr::destroy()
{
	pthread_mutexattr_destroy(&m_mutex_attr);
}


Mutex::Mutex(MutexAttr mutex_attr)
	: m_mutex_attr(mutex_attr)
{
	pthread_mutexattr_t& attr = m_mutex_attr.m_mutex_attr;
133
134
	int ret = pthread_mutex_init(&m_mutex, &attr);
	check_error(ret, "Error initializing mutex");
ahoms's avatar
ahoms committed
135
136
137
138
139
140
141
142
143
}

Mutex::~Mutex()
{
	pthread_mutex_destroy(&m_mutex);
}

void Mutex::lock()
{
144
145
	int ret = pthread_mutex_lock(&m_mutex);
	check_error(ret, "Error locking mutex");
ahoms's avatar
ahoms committed
146
147
148
149
}

void Mutex::unlock()
{
150
151
	int ret = pthread_mutex_unlock(&m_mutex);
	check_error(ret, "Error unlocking mutex");
ahoms's avatar
ahoms committed
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
}

bool Mutex::tryLock()
{
	
	switch (pthread_mutex_trylock(&m_mutex)) {
	case EBUSY:
		return false;
	case 0:
		return true;
	default:
		throw LIMA_COM_EXC(Error, "Error trying to lock mutex");
	}
}

MutexAttr Mutex::getAttr()
{
	return m_mutex_attr;
}


173
Cond::Cond() : m_mutex(MutexAttr::Normal)
ahoms's avatar
ahoms committed
174
{
175
176
	int ret = pthread_cond_init(&m_cond, NULL);
	check_error(ret, "Error initializing condition");
ahoms's avatar
ahoms committed
177
178
179
180
181
182
183
}

Cond::~Cond()
{
	pthread_cond_destroy(&m_cond);
}

184
185
186
187
188
189
190
191
192
193
194
195
196
/** @brief wait on cond variable
 *  @return 
 *  - true if ok 
 *  - false if timeout
 */
bool Cond::wait(double timeout)
{
  int retcode = 0;
  if(timeout >= 0.)
    {
      struct timeval now;
      struct timespec waitTimeout;
      gettimeofday(&now,NULL);
197
      waitTimeout.tv_sec = now.tv_sec + time_t(timeout);
198
199
      waitTimeout.tv_nsec = (now.tv_usec * 1000) + 
	long((timeout - long(timeout)) * 1e9);
200
201
      if(waitTimeout.tv_nsec >= 1000000000L) // Carry
	++waitTimeout.tv_sec,waitTimeout.tv_nsec -= 1000000000L;
202
203
204
205
206
      retcode = pthread_cond_timedwait(&m_cond,&m_mutex.m_mutex,&waitTimeout);
    }
  else
      retcode = pthread_cond_wait(&m_cond, &m_mutex.m_mutex);
	
207
208
  if(retcode != ETIMEDOUT)
    check_error(retcode, "Error waiting for condition");
209
  return !retcode;
ahoms's avatar
ahoms committed
210
211
212
213
}

void Cond::signal()
{
214
215
	int ret = pthread_cond_signal(&m_cond);
	check_error(ret, "Error signaling condition");
ahoms's avatar
ahoms committed
216
217
}

218
219
220
221
222
223
224
225
226
227
void Cond::acquire()
{
	m_mutex.lock();
}

void Cond::release()
{
	m_mutex.unlock();
}

228
229
void Cond::broadcast()
{
230
231
	int ret = pthread_cond_broadcast(&m_cond);
	check_error(ret, "Error broadcast condition");
232
}
ahoms's avatar
ahoms committed
233

234
pid_t lima::GetThreadID() {
235
236
237
238

#if defined(_WIN32)
	return GetCurrentThreadId();
#else
239
	return syscall(SYS_gettid);
240
241
#endif
	
242
243
}

244
245
246
247
248
249
250
251
252
253
Thread::ExceptionCleanUp::ExceptionCleanUp(Thread& thread)
	: m_thread(thread)
{
}

Thread::ExceptionCleanUp::~ExceptionCleanUp()
{
	m_thread.m_exception_handled = true;
}

254
255
256
Thread::Thread()
	: m_thread(0), m_started(false), m_finished(false),
	  m_exception_handled(false), m_tid(0)
ahoms's avatar
ahoms committed
257
{
Florent Langlois's avatar
Florent Langlois committed
258
	pthread_attr_init(&m_thread_attr);
ahoms's avatar
ahoms committed
259
260
261
262
}

Thread::~Thread()
{
263
264
	if (m_started)
		join();
Florent Langlois's avatar
Florent Langlois committed
265
	pthread_attr_destroy(&m_thread_attr);
ahoms's avatar
ahoms committed
266
267
268
269
270
271
272
}

void Thread::start()
{
	if (m_started)
		throw LIMA_COM_EXC(Error, "Thread already started");

273
	m_finished = false;
274
275
276
	int ret = pthread_create(&m_thread, &m_thread_attr,
				 staticThreadFunction, this);
	check_error(ret, "Error creating thread");
ahoms's avatar
ahoms committed
277
278
279
280

	m_started = true;
}

Florent Langlois's avatar
Florent Langlois committed
281
void Thread::join()
ahoms's avatar
ahoms committed
282
283
{
	if (!m_started)
284
		throw LIMA_COM_EXC(Error, "Thread not started or joined");
ahoms's avatar
ahoms committed
285

286
287
	pthread_join(m_thread, NULL);
	m_started = false;
ahoms's avatar
ahoms committed
288
289
290
291
292
293
294
295
296
297
298
299
}

bool Thread::hasStarted()
{
	return m_started;
}

bool Thread::hasFinished()
{
	return m_finished;
}

300
301
302
303
304
pid_t Thread::getThreadID()
{
	return m_tid;
}

ahoms's avatar
ahoms committed
305
306
void *Thread::staticThreadFunction(void *data)
{
307
308
	using namespace std;

ahoms's avatar
ahoms committed
309
	Thread *thread = (Thread *) data;
310
	thread->m_tid = GetThreadID();
ahoms's avatar
ahoms committed
311
312
313
314

	try {
		thread->threadFunction();
	} catch (...) {
315
316
		if (!thread->m_exception_handled) {
			ostream& os = cerr;
317
318
			long long thread_id = (long long) pthread_self();
			std::streamsize w = os.width();
319
320
321
322
323
			os << "***** Thread " 
			   << setw(8) << hex << thread_id << setw(w) << dec
			   << " function exited due to an exception "
			   << "without clean-up! *****" << endl;
		}
ahoms's avatar
ahoms committed
324
325
326
327
328
329
330
	}
	
	thread->m_finished = true;
	return NULL;
}

CmdThread::AuxThread::AuxThread(CmdThread& master)
331
	: m_master(&master)
ahoms's avatar
ahoms committed
332
333
334
335
336
337
338
339
340
{
}

CmdThread::AuxThread::~AuxThread()
{
}

void CmdThread::AuxThread::threadFunction()
{
341
	m_master->cmdLoop();
ahoms's avatar
ahoms committed
342
343
344
345
346
}

CmdThread::CmdThread()
	: m_thread(*this)
{
347
348
	m_status = InInit;
	m_status_history.set(InInit);
ahoms's avatar
ahoms committed
349
350
351
352
}

CmdThread::~CmdThread()
{
353
354
355
356
357
358
359
360
	using namespace std;

	if (!m_thread.hasStarted())
		return;

	if (getStatus() != Finished) {
		cerr << "***** Error: CmdThread did not call abort "
		     << "in the derived class destructor! *****";
361
362
		abort();
	}
ahoms's avatar
ahoms committed
363
364
}

365
AutoMutex CmdThread::lock() const
ahoms's avatar
ahoms committed
366
{
367
	return AutoMutex(m_cond.mutex(), AutoMutex::Locked);
ahoms's avatar
ahoms committed
368
369
}

370
AutoMutex CmdThread::tryLock() const
ahoms's avatar
ahoms committed
371
{
372
	return AutoMutex(m_cond.mutex(), AutoMutex::TryLocked);
ahoms's avatar
ahoms committed
373
374
}

375
int CmdThread::getStatus() const
ahoms's avatar
ahoms committed
376
{
377
	AutoMutex l = lock();
378
	return m_status;
ahoms's avatar
ahoms committed
379
380
}

381
382
int CmdThread::getNextCmd() const
{
383
384
	AutoMutex l = lock();
	return m_cmd.empty() ? None : m_cmd.front();
385
386
}

ahoms's avatar
ahoms committed
387
388
389
void CmdThread::setStatus(int status)
{
	AutoMutex l = lock();
390
391
	m_status = status;
	m_status_history.set(status);
ahoms's avatar
ahoms committed
392
393
394
395
396
397
	m_cond.signal();
}

void CmdThread::waitStatus(int status)
{
	AutoMutex l = lock();
398
	while (!m_status_history.test(status))
399
		m_cond.wait();
ahoms's avatar
ahoms committed
400
401
402
403
}

int CmdThread::waitNotStatus(int status)
{
404
405
	std::bitset<16> mask(0xffff);
	mask.reset(status);
406

407
408
	AutoMutex l = lock();
	while ((m_status_history & mask).none())
409
410
		m_cond.wait();
	return m_status;
ahoms's avatar
ahoms committed
411
412
413
414
415
}

void CmdThread::sendCmd(int cmd)
{
	AutoMutex l = lock();
416
	doSendCmd(cmd);
ahoms's avatar
ahoms committed
417
}
418

419
420
421
422
/** @brief send a command only if the return of if_test is true.
 *  
 *  function if_test get as argument the command and status
 */
423
void CmdThread::sendCmdIf(int cmd, bool (*if_test)(int,int))
424
{
425
	AutoMutex l = lock();
426
427
428

	if (if_test && if_test(cmd, m_status))
		doSendCmd(cmd);
429
430
}

431
void CmdThread::doSendCmd(int cmd)
432
{
433
	if (m_status == Finished)
434
		throw LIMA_COM_EXC(Error, "Thread has Finished");
435

436
437
438
	// Assume that we will have a call to waitStatus somewhere after the new command
	m_status_history.reset();

439
440
	m_cmd.push(cmd);
	m_cond.signal();
441
}
442

ahoms's avatar
ahoms committed
443
444
445
446
447
void CmdThread::start()
{
	if (m_thread.hasStarted())
		throw LIMA_COM_EXC(InvalidValue, "Thread already started");

448
	m_cmd.push(Init);
ahoms's avatar
ahoms committed
449
450
451
452
453
	m_thread.start();
}

void CmdThread::abort()
{
454
455
456
457
458
	if (getStatus() == Finished)
		return;

	sendCmd(Abort);
	waitStatus(Finished);
ahoms's avatar
ahoms committed
459
460
461
462
463
464
}

int CmdThread::waitNextCmd()
{
	AutoMutex l = lock();

465
466
	while (m_cmd.empty())
		m_cond.wait();
ahoms's avatar
ahoms committed
467

468
469
	int cmd = m_cmd.front();
	m_cmd.pop();
ahoms's avatar
ahoms committed
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
	return cmd;
}

void CmdThread::cmdLoop()
{
	while (getStatus() != Finished) {
		int cmd = waitNextCmd();
		switch (cmd) {
		case None:
			throw LIMA_COM_EXC(InvalidValue, "Invalid None cmd");
		case Init:
			init();
			break;
		case Abort:
			setStatus(Finished);
			break;
		default:
			execCmd(cmd);
		}
	}
}