/ani/mrses

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

#include "hw_thread.h"

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 = runs[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) {
		fprintf(stderr, "Error exectuing code, %i\n", err);
		pthread_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);

    pthread_exit(NULL);
}

HWThread hw_thread_create(HWSched sched, int thread_id, void *hwctx, HWRunFunction *run_func, HWFreeFunction free_func) {
    int 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;
    
    err = pthread_create(&ctx->thread, NULL, (void*(*)(void*))hw_thread_function, ctx);
    if (err) {
	fprintf(stderr, "Error spawn thread, errno: %i\n", errno);
	hw_thread_destroy(ctx);
	return NULL;
    }
    
    return ctx;
}

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