File: multithread.c

package info (click to toggle)
gnubg 0.90-3
  • links: PTS, VCS
  • area: main
  • in suites: lenny
  • size: 30,800 kB
  • ctags: 8,224
  • sloc: ansic: 92,884; xml: 13,338; sh: 9,675; makefile: 425; python: 392; yacc: 295; sql: 237; lex: 220; php: 102; cs: 81; awk: 25; sed: 16
file content (684 lines) | stat: -rw-r--r-- 14,421 bytes parent folder | download
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
/* This program is free software; you can redistribute it and/or modify
 * it under the terms of version 3 or later of the GNU General Public License as
 * published by the Free Software Foundation.
 *
 * This program 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, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include "config.h"
#if USE_MULTITHREAD
#ifdef WIN32
#include <windows.h>
#include <process.h>
#endif
#include <stdlib.h>
#include <stdio.h>
#include <glib.h>
#include <glib/gthread.h>
#if USE_GTK
#include <gtk/gtk.h>
#include <gtkgame.h>
#endif

#include "multithread.h"
#include "speed.h"
#include "rollout.h"
#include "util.h"

#define UI_UPDATETIME 250

#if __GNUC__
#define GCC_ALIGN_HACK 1
#endif

#if TRY_COUNTING_PROCEESING_UNITS
extern int GetLogicalProcssingUnitCount(void);
#endif

#ifdef GLIB_THREADS
typedef struct _ManualEvent
{
    GCond* cond;
    int signalled;
} *ManualEvent;
typedef GPrivate* TLSItem;
typedef GCond* Event;
typedef GMutex* Mutex;
GMutex* condMutex=NULL;    /* Extra mutex needed for waiting */
GAsyncQueue *async_queue=NULL; /* Needed for async waiting */
#else
typedef HANDLE ManualEvent;
typedef DWORD TLSItem;
typedef HANDLE Event;
typedef HANDLE Mutex;
#endif

typedef struct _ThreadData
{
    ManualEvent activity;
    TLSItem tlsItem;
    Event alldone;
    Mutex queueLock;
    Mutex multiLock;
	ManualEvent syncStart;
	ManualEvent syncEnd;

    int addedTasks;
    int doneTasks;
    int totalTasks;

    GList *tasks;
    int result;
} ThreadData;

ThreadData td;

static double start; /* used for timekeeping */
static unsigned int numThreads = 0;

#ifdef GLIB_THREADS

static void TLSCreate(TLSItem *pItem)
{
    *pItem = g_private_new(free);
}

static void TLSFree(TLSItem pItem)
{	/* Done automaticaly by glib */
}

static void TLSSetValue(TLSItem pItem, int value)
{
	int *pNew = (int*)malloc(sizeof(int));
	*pNew = value;
    g_private_set(pItem, (gpointer)pNew);
}

#define TLSGet(item) *((int*)g_private_get(item))

static void InitEvent(Event *pEvent)
{
    *pEvent = g_cond_new();
}

static void FreeEvent(Event event)
{
    g_cond_free(event);
}

static void InitManualEvent(ManualEvent *pME)
{
    ManualEvent pNewME = malloc(sizeof(*pNewME));
    pNewME->cond = g_cond_new();
    pNewME->signalled = FALSE;
    *pME = pNewME;
}

static void FreeManualEvent(ManualEvent ME)
{
    g_cond_free(ME->cond);
    free(ME);
}

static void WaitForManualEvent(ManualEvent ME)
{
	GTimeVal tv;
	multi_debug("wait for manual event locks");
	g_mutex_lock(condMutex);
	while (!ME->signalled) {
		multi_debug("waiting for manual event");
		g_get_current_time(&tv);
		g_time_val_add(&tv, 10 * 1000 * 1000);
		if (g_cond_timed_wait(ME->cond, condMutex, &tv))
			break;
		else
		{
			multi_debug("still waiting for manual event");
		}
	}

	g_mutex_unlock(condMutex);
	multi_debug("wait for manual event unlocks");
}

static void ResetManualEvent(ManualEvent ME)
{
	multi_debug("reset manual event locks");
    g_mutex_lock(condMutex);
    ME->signalled = FALSE;
    g_mutex_unlock(condMutex);
	multi_debug("reset manual event unlocks");
}

static void SetManualEvent(ManualEvent ME)
{
	multi_debug("reset manual event locks");
    g_mutex_lock(condMutex);
    ME->signalled = TRUE;
    g_cond_broadcast(ME->cond);
    g_mutex_unlock(condMutex);
	multi_debug("reset manual event unlocks");
}

static void InitMutex(Mutex *pMutex)
{
    *pMutex = g_mutex_new();
}

static void FreeMutex(Mutex mutex)
{
    g_mutex_free(mutex);
}

#define Mutex_Lock(mutex) g_mutex_lock(mutex)
#define Mutex_Release(mutex) g_mutex_unlock(mutex)

#else    /* win32 */

static void TLSCreate(TLSItem *ppItem)
{
    *ppItem = TlsAlloc();
	if (*ppItem == TLS_OUT_OF_INDEXES)
		PrintSystemError("calling TlsAlloc");
}

static void TLSFree(TLSItem pItem)
{
	free(TlsGetValue(pItem));
	TlsFree(pItem);
}

static void TLSSetValue(TLSItem pItem, int value)
{
	int *pNew = (int*)malloc(sizeof(int));
	*pNew = value;
    if (TlsSetValue(pItem, pNew) == 0)
		PrintSystemError("calling TLSSetValue");
}

#define TLSGet(item) *((int*)TlsGetValue(item))

static void InitEvent(Event *pEvent)
{
    *pEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
	if (*pEvent == NULL)
		PrintSystemError("creating event");
}

static void FreeEvent(Event event)
{
    CloseHandle(event);
}

static void InitManualEvent(ManualEvent *pME)
{
    *pME = CreateEvent(NULL, TRUE, FALSE, NULL);
	if (*pME == NULL)
		PrintSystemError("creating manual event");
}

static void FreeManualEvent(ManualEvent ME)
{
    CloseHandle(ME);
}

#define WaitForManualEvent(ME) WaitForSingleObject(ME, INFINITE)
#define ResetManualEvent(ME) ResetEvent(ME)
#define SetManualEvent(ME) SetEvent(ME)

static void InitMutex(Mutex *pMutex)
{
    *pMutex = CreateMutex(NULL, FALSE, NULL);
	if (*pMutex == NULL)
		PrintSystemError("creating mutex");
}

static void FreeMutex(Mutex mutex)
{
    CloseHandle(mutex);
}

#define Mutex_Lock(mutex) WaitForSingleObject(mutex, INFINITE)
#define Mutex_Release(mutex) ReleaseMutex(mutex)

#endif


extern unsigned int MT_GetNumThreads(void)
{
    return numThreads;
}

extern int MT_Enabled(void)
{
    return TRUE;
}

static void MT_CloseThreads(void)
{
    mt_add_tasks(numThreads, TT_CLOSE, NULL);
    if (MT_WaitForTasks(NULL, 0) != (int)numThreads)
		g_print("Error closing threads!\n");
}

static void MT_TaskDone(Task *pt)
{
    MT_SafeInc(&td.doneTasks);
#ifndef GLIB_THREADS
	if (td.doneTasks >= td.totalTasks)
		SetEvent(td.alldone);
#endif

    if (pt)
    {
        free(pt->pLinkedTask);
        free(pt);
    }
}

static Task *MT_GetTask(void)
{
    Task *task = NULL;
    if (g_list_length(td.tasks) > 0)
    {
        task = (Task*)g_list_first(td.tasks)->data;
        td.tasks = g_list_delete_link(td.tasks, g_list_first(td.tasks));
        if (g_list_length(td.tasks) == 0)
        {
            ResetManualEvent(td.activity);
        }
    }
    return task;
}

static void MT_AbortTasks(void)
{
    Task *task;
    multi_debug("abort tasks: lock");
    Mutex_Lock(td.queueLock);

    /* Remove tasks from list */
    while ((task = MT_GetTask()) != NULL)
        MT_TaskDone(task);

    Mutex_Release(td.queueLock);
    multi_debug("abort tasks: release");
}

static int MT_DoTask(void)
{
    int alive = TRUE;
    Task *task;

    multi_debug("do tasks: lock");
    Mutex_Lock(td.queueLock);
    task = MT_GetTask();
    Mutex_Release(td.queueLock);
    multi_debug("do tasks: release");

    if (task)
    {
        switch (task->type)
        {
        case TT_ANALYSEMOVE:
        {
            float doubleError;
            AnalyseMoveTask *amt;
AnalyzeDoubleDecison:
            amt = (AnalyseMoveTask *)task;
            if (AnalyzeMove (amt->pmr, &amt->ms, amt->plGame, amt->psc,
                        &esAnalysisChequer,
                        &esAnalysisCube, aamfAnalysis,
                        afAnalysePlayers, &doubleError ) < 0 )
            {
                MT_AbortTasks();
                td.result = -1;
            }
            if (task->pLinkedTask)
            {    /* Need to analyze take/drop decision in sequence */
                task = task->pLinkedTask;
                goto AnalyzeDoubleDecison;
            }
            break;
        }
        case TT_ROLLOUTLOOP:
            RolloutLoopMT();
            break;
		case TT_RUNCALIBRATIONEVALS:
			RunEvals();
			break;
		case TT_ASYNCTASK:
		{
			AsyncTask *asynctask = (AsyncTask *)task;
			td.result = asynctask->fun(asynctask->data);
			break;
		}
        case TT_TEST:
            printf("Test: waiting for a second");
            g_usleep(1000 * 1000);
            break;
        case TT_CLOSE:
			MT_SafeInc(&td.result);
            alive = FALSE;
            break;
        }
	multi_debug("task done: lock");
        Mutex_Lock(td.queueLock);
        MT_TaskDone(task);
        Mutex_Release(td.queueLock);
	multi_debug("task done: release");
        return alive;
    }
    else
        return -1;
}

#if GCC_ALIGN_HACK

static unsigned int MT_ActualWorkerThreadFunction(void *id);
#ifdef GLIB_THREADS
static gpointer
#else
static void 
#endif
MT_WorkerThreadFunction(gpointer id)
{    /* Align stack and call actual function */
	asm  __volatile__  ("andl $-16, %%esp" : : : "%esp");
	MT_ActualWorkerThreadFunction(id);
#ifdef GLIB_THREADS
return NULL;
#endif
}

unsigned int MT_ActualWorkerThreadFunction(void *id)
#else
#ifdef GLIB_THREADS
static gpointer
#else
static unsigned int
#endif
MT_WorkerThreadFunction(void *id)
#endif
{
	int *pID = (int*)id;
    TLSSetValue(td.tlsItem, *pID);
    free(pID);
	MT_SafeInc(&td.result);
    MT_TaskDone(NULL);    /* Thread created */
    do
    {
        WaitForManualEvent(td.activity);
    } while (MT_DoTask());

#ifdef GLIB_THREADS
	g_usleep(0);	/* Avoid odd crash */
#endif

	return 0;
}

static gboolean WaitForAllTasks(int time)
{
#ifndef GLIB_THREADS
	if (WaitForSingleObject(td.alldone, time) != WAIT_TIMEOUT)
#else
	int j=0;
	while (td.doneTasks != td.totalTasks && j++ < 10)
		g_usleep(100*time);
	if (td.doneTasks == td.totalTasks)
#endif
	{
		td.doneTasks = td.totalTasks = td.addedTasks = 0;
		return TRUE;
	}
	else
		return FALSE;	/* Not done yet */
}

static void WaitingForThreads(void)
{	/* Unlikely to be called */
	multi_debug("Waiting for threads to be created!");
}

static void MT_CreateThreads(void)
{
    unsigned int i;
	td.addedTasks = td.totalTasks = numThreads;
	td.result = 0;
    for (i = 0; i < numThreads; i++)
    {
    	int *pID = (int*)malloc(sizeof(int));
    	*pID = i;
#ifdef GLIB_THREADS
        if (!g_thread_create(MT_WorkerThreadFunction, pID, FALSE, NULL))
#else
        if (_beginthread(MT_WorkerThreadFunction, 0, pID) == 0)
#endif
            printf("Failed to create thread\n");
    }
	/* Wait for all the threads to be created (timeout after 2 seconds) */
	if (MT_WaitForTasks(WaitingForThreads, 1000) != (int)numThreads)
		g_print("Error creating threads!\n");
}

void MT_SetNumThreads(unsigned int num)
{
	if (num != numThreads)
	{
		MT_CloseThreads();
		numThreads = num;
		MT_CreateThreads();
	}
}

extern void MT_InitThreads(void)
{
#ifdef GLIB_THREADS
	if (!g_thread_supported ())
		g_thread_init (NULL);
	g_assert(g_thread_supported());
#endif

    td.tasks = NULL;
	td.doneTasks = td.totalTasks = td.addedTasks = 0;
    InitManualEvent(&td.activity);
    TLSCreate(&td.tlsItem);
	TLSSetValue(td.tlsItem, 0);	/* Main thread shares id 0 */
    InitEvent(&td.alldone);
    InitMutex(&td.multiLock);
    InitMutex(&td.queueLock);
	InitManualEvent(&td.syncStart);
	InitManualEvent(&td.syncEnd);
#ifdef GLIB_THREADS
    if (condMutex == NULL)
        condMutex = g_mutex_new();
#endif
}

extern void MT_StartThreads(void)
{
    if (numThreads == 0)
	{
#if TRY_COUNTING_PROCEESING_UNITS
        numThreads = GetLogicalProcssingUnitCount();
#else
        numThreads = 1;
#endif
		MT_CreateThreads();
	}
}

void MT_AddTask(Task *pt, gboolean lock)
{
	if (lock)
	{
		multi_debug("add task: lock");
		Mutex_Lock(td.queueLock);
	}
	td.addedTasks++;
	td.tasks = g_list_append(td.tasks, pt);
	if (g_list_length(td.tasks) == 1)
	{    /* First task */
		td.result = 0;
		SetManualEvent(td.activity);
	}
	if (lock)
	{
		Mutex_Release(td.queueLock);
		multi_debug("add task: release");
	}
}

void mt_add_tasks(int num_tasks, TaskType tt, gpointer linked)
{
	int i;
	multi_debug("add many tasks: lock");
	Mutex_Lock(td.queueLock);
	td.totalTasks = num_tasks;
	for (i = 0; i < num_tasks; i++)
	{
		Task *pt = (Task*)malloc(sizeof(Task));
		pt->type = tt;
		pt->pLinkedTask = linked;
		MT_AddTask((Task*)pt, FALSE);
	}
	Mutex_Release(td.queueLock);
	multi_debug("add many release: lock");
}

int MT_WaitForTasks(void (*pCallback)(void), int callbackTime)
{
    int callbackLoops = callbackTime / UI_UPDATETIME;
    int waits = 0;
	int polltime = callbackLoops ? UI_UPDATETIME : callbackTime;

	if (td.addedTasks == 0)
		return 0;

    multi_debug("wait for tasks: lock(1)");
    Mutex_Lock(td.queueLock);
    td.totalTasks = td.addedTasks;
    Mutex_Release(td.queueLock);
    multi_debug("wait for tasks: release(1)");

	multi_debug("while waiting for all tasks");
    while (!WaitForAllTasks(polltime))
    {
        waits++;
        if (pCallback && waits >= callbackLoops)
        {
            waits = 0;
            pCallback();
        }

#if USE_GTK
		else
		{
			GTKSuspendInput();
			while(gtk_events_pending())
				gtk_main_iteration();
			GTKResumeInput();
		}
#endif
    }
	multi_debug("done while waiting for all tasks");

    return td.result;
}

extern void MT_Close(void)
{
    MT_CloseThreads();

    FreeManualEvent(td.activity);
    FreeEvent(td.alldone);
    FreeMutex(td.multiLock);

    /* queueLock is locked around MT_TaskDone and may not be released in time
     * unless we wait for it here before we free the mutex */
    Mutex_Lock(td.queueLock);
    Mutex_Release(td.queueLock);
    FreeMutex(td.queueLock);

    FreeManualEvent(td.syncStart);
    FreeManualEvent(td.syncEnd);
    TLSFree(td.tlsItem);
}

extern int MT_GetThreadID(void)
{
    return TLSGet(td.tlsItem);
}

extern void MT_Exclusive(void)
{
	Mutex_Lock(td.multiLock);
}

extern void MT_Release(void)
{
	Mutex_Release(td.multiLock);
}

extern int MT_GetDoneTasks(void)
{
    return td.doneTasks;
}

extern void MT_SyncInit(void)
{
	ResetManualEvent(td.syncStart);
	ResetManualEvent(td.syncEnd);
}

extern void MT_SyncStart(void)
{
	static int count = 0;

	/* Wait for all threads to get here */
	if (MT_SafeIncValue(&count) == (int)numThreads)
	{
		count--;
		start = get_time();
		SetManualEvent(td.syncStart);
	}
	else
	{
		WaitForManualEvent(td.syncStart);
		if (MT_SafeDecCheck(&count))
			ResetManualEvent(td.syncStart);
	}
}

extern double MT_SyncEnd(void)
{
	static int count = 0;
	double now;

	/* Wait for all threads to get here */
	if (MT_SafeIncValue(&count) == (int)numThreads)
	{
		now = get_time();
		count--;
		SetManualEvent(td.syncEnd);
		return now - start;
	}
	else
	{
		WaitForManualEvent(td.syncEnd);
		if (MT_SafeDecCheck(&count))
			ResetManualEvent(td.syncEnd);
		return 0;
	}
}
#else
/* Avoid no code warning */
extern int dummy;
#endif