DAY 10
0

經典範例

PS：我覺得 C 語言的程式碼，我現在這種寫法的可讀性很低＝＝ Sorry

``````typedef struct __NODE {
int val;
struct __NODE *next;
} NODE;
``````
• Coarse-Grained Synchronization
``````typedef struct __NODE {
int val;
struct __NODE *next;
} NODE;

typedef struct {
} LIST;
``````

``````void add(NODE *head, int newVal) {
NODE *curr, *pred;

curr = pred->next;
while(curr->val < newVal) {
pred = curr;
curr = curr->next;
}
NODE *new = malloc(sizeof(NODE));
new->val = newVal;
new->next = curr;
pred->next = new;

}
``````
• Fine-Grained Synchronization
``````typedef struct __NODE {
int val;
struct __NODE *next;
} NODE;
``````

``````void add(NODE *head, int newVal) {
NODE *pred;

Node *curr = pred->next;
while(curr->val < newVal) {
pred = curr;
curr = curr->next;
}
NODE *new = malloc(sizeof(NODE));
new->val = newVal;
new->next = curr;
pred->next = new;

}
``````
• Optimistic Synchronization

``````// 確認是否還連在一起
int validate(NODE *head, NODE *pred, NODE *curr) {
while(node->val <= pred->val) {
if(node == pred)
return pred->next == curr;
node = node->next;
}

return 0;
}

while(true) {
NODE *curr = pred->next;

while(curr->val <= newVal) {
pred = curr; curr = curr->next;
}
// 先執行 while 搜尋後，才開始

NODE *new = malloc(sizeof(NODE));
new->val = newVal;
new->next = curr;
pred->next = new;
}

}
}
``````
• Lazy Synchronization

``````typedef struct __NODE {
int val;
int marked;
struct __NODE *next;
} NODE;
``````
``````int validate(NODE *pred, NODE *curr) {
return !pred->marked && !curr->marked && pred->next==curr;
}

while(true) {
NODE *curr = pred->next;

while(curr->val <= newVal) {
pred = curr; curr = curr->next;
}
// 先執行 while 搜尋後，才開始

if(validate(pred, curr)) {
NODE *new = malloc(sizeof(NODE));
new->marked = 0;
new->val = newVal;
new->next = curr;
pred->next = new;
}

}
}
``````

``````typedef struct _task {
void (*func)(void *);   /**< Pointer to task function */
void *arg;              /**< Pointer to the arguments passed to _func_ */

typedef struct {
pthread_mutex_t mutex;  /**< The mutex lock of this queue */
pthread_cond_t cond;    /**< The conitional variable of this queue */
uint32_t size;          /**< The size of the queue */
uint32_t num_of_consumed;   /**< The number of consumed tasks */
} tqueue_t;

typedef struct {
uint32_t count;     /**< Number of working threads */
tqueue_t *queue;    /**< Pointer to the task queue */
} tpool_t;
``````

• `task_t`
function pointer 用來指示要呼叫什麼 function
void* 用來存取任意型態的參數

• `tqueue_t`
與一般的 Queue 相比，多了 mutex lock 以及 conditional variable

• `tpool_t`
queue 為任務列表