CA project 常用操作
coconutnut

很久没用C了,还有一些同步相关的操作,记录一下。

内存

分配

1
2
3
4
struct region* region = (struct region*) malloc(sizeof(struct region));
if (unlikely(!region)) {
return false;
}

分配(且内存按align排列)

1
2
3
if (posix_memalign(&(region->start), align, size) != 0) {
free(region);
}

填零

1
memset(region->start, 0, size);

指针

填值&取值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// define index
struct segment {
size_t align;
uint8_t* index;
};

// init index
for(size_t i=0; i<cnt; i++){
size_t* p = (size_t*)(segment->index + i*align);
*p = i;
}

// get index
size_t index = *(size_t*)(address)

🌰

1
2
3
4
// find segment and index
size_t index = *(size_t*)(address);
size_t offset = index * region->align + sizeof(struct segment);
struct segment* segment = (struct segment*)((uint8_t*)address - offset);

指针的指针

1
2
3
4
5
6
7
8
9
10
11
12
struct s {
void** p_addr;
size_t* p_num;
};

// set
*(s->p_addr + index) = address; // void* address
*(s->p_num + index) = size; // size_t size

// get
void* addr = *(p_addr + i);
size_t size = *(p_num + i);

位运算

设置mask

1
static const size_t MASK = 0x0001 << 2;

获取mask下的值

1
#define GET_FLAG(control, mask) ((atomic_load(control) & mask) != 0)

设置高位

1
control |= id << 32;

获取高位

1
uint_least64_t id = control >> 32;

同步

锁和条件变量

reference “lock.h” “lock.c”

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
#include <pthread.h>

struct lock_t {
pthread_mutex_t mutex;
pthread_cond_t cv;
};

bool lock_init(struct lock_t* lock) {
return pthread_mutex_init(&(lock->mutex), NULL) == 0
&& pthread_cond_init(&(lock->cv), NULL) == 0;
}

void lock_cleanup(struct lock_t* lock) {
pthread_mutex_destroy(&(lock->mutex));
pthread_cond_destroy(&(lock->cv));
}

bool lock_acquire(struct lock_t* lock) {
return pthread_mutex_lock(&(lock->mutex)) == 0;
}

void lock_release(struct lock_t* lock) {
pthread_mutex_unlock(&(lock->mutex));
}

void lock_wait(struct lock_t* lock) {
pthread_cond_wait(&(lock->cv), &(lock->mutex));
}

void lock_wake_up(struct lock_t* lock) {
pthread_cond_broadcast(&(lock->cv));
}

原子变量

atomic_load

atomic_store

atomic_fetch_add

atomic_compare_exchange