/normxcorr/trunk

To get this branch, use:
bzr branch http://suren.me/webbzr/normxcorr/trunk
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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "normxcorr_hw_msg.h"

#include "hw_sched.h"
#include "hw_thread.h"

#ifdef HW_SINGLE_MODE
# define hw_run_entry(entry) entry
#else /* HW_SINGLE_MODE */
# define hw_run_entry(entry) runs[entry]
#endif /* HW_SINGLE_MODE */

static void *hw_thread_function(HWThread ctx) {
    int err;
    int chunk_id;
    
    HWRunFunction *runs;
    HWRunFunction run;
    HWSched sched;
    void *hwctx;
    
    sched = ctx->sched;
    runs = ctx->run;
    hwctx = ctx->hwctx;
    
    hw_sched_lock(sched, job_cond);

    hw_sched_lock(sched, compl_cond);
    ctx->status = HW_THREAD_STATUS_IDLE;    
    hw_sched_broadcast(sched, compl);
    hw_sched_unlock(sched, compl_cond);
    
    while (sched->status) {
	hw_sched_wait(sched, job);
	if (!sched->status) break;

	hw_sched_unlock(sched, job_cond);
	
	run = hw_run_entry(sched->entry);
	chunk_id = hw_sched_get_chunk(sched, ctx->thread_id);

	    /* Should be after get_chunk, since we can check if it's first time */
	ctx->status = HW_THREAD_STATUS_RUNNING; 
	while (chunk_id >= 0) {
	    err = run(ctx, hwctx, chunk_id, sched->ctx);
	    if (err) {
		reportError("Error exectuing code, %i\n", err);
		g_thread_exit(NULL);
	    }
	    chunk_id = hw_sched_get_chunk(sched, ctx->thread_id);
	}

	hw_sched_lock(sched, job_cond);
	
	hw_sched_lock(sched, compl_cond);
	ctx->status = HW_THREAD_STATUS_DONE;
	hw_sched_broadcast(sched, compl);
	hw_sched_unlock(sched, compl_cond);
    }

    hw_sched_unlock(sched, job_cond);

    g_thread_exit(NULL);
}

HWThread hw_thread_create(HWSched sched, int thread_id, void *hwctx, HWRunFunction *run_func, HWFreeFunction free_func) {
    GError *err;
    
    HWThread ctx;
    
    ctx = (HWThread)malloc(sizeof(HWThreadS));
    if (!ctx) return ctx;
    
    memset(ctx, 0, sizeof(HWThreadS));

    ctx->sched = sched;
    ctx->hwctx = hwctx;
    ctx->run = run_func;
    ctx->free = free_func;
    ctx->thread_id = thread_id;
    ctx->status = HW_THREAD_STATUS_INIT;
    
    ctx->thread = g_thread_create((GThreadFunc)hw_thread_function, ctx, 1, &err);
    if (!ctx->thread) {
	reportError("Error spawn thread, errno: %i\n", err->message);
	g_error_free(err);

	hw_thread_destroy(ctx);
	return NULL;
    }
    
    return ctx;
}

void hw_thread_destroy(HWThread ctx) {
    if (ctx->thread) {
	g_thread_join(ctx->thread);
    }
    
    if (ctx->data) {
	free(ctx->data);
    }
    
    if (ctx->free) {
	ctx->free(ctx->hwctx);
    }
    
    free(ctx);
}