Lab6: Multithreading

Uthread: switching between threads

uthread.c

struct context
{
	uint64 ra;
	uint64 sp;

	// callee-saved
	uint64 s0;
	uint64 s1;
	uint64 s2;
	uint64 s3;
	uint64 s4;
	uint64 s5;
	uint64 s6;
	uint64 s7;
	uint64 s8;
	uint64 s9;
	uint64 s10;
	uint64 s11;
};

struct thread
{
	char stack[STACK_SIZE]; /* the thread's stack */
	int state;				/* FREE, RUNNING, RUNNABLE */
	struct context context;
};
void thread_schedule(void)
{
	......

	if (current_thread != next_thread)
	{ /* switch threads?  */
		next_thread->state = RUNNING;
		t = current_thread;
		current_thread = next_thread;
		thread_switch((uint64)&t->context, (uint64)&current_thread->context);
	}
	else
		next_thread = 0;
}
void thread_create(void (*func)())
{
	struct thread *t;

	for (t = all_thread; t < all_thread + MAX_THREAD; t++)
	{
		if (t->state == FREE)
			break;
	}

	memset(&t->stack, 0, STACK_SIZE);
	t->state = RUNNABLE;
	memset(&t->context, 0, sizeof(t->context));
	t->context.sp = (uint64)(t->stack + STACK_SIZE);
	t->context.ra = (uint64)func;
}

 uthread_switch.S

	.text

	/*
         * save the old thread's registers,
         * restore the new thread's registers.
         */

.globl thread_switch
thread_switch:
	sd ra, 0(a0)
    sd sp, 8(a0)
    sd s0, 16(a0)
    sd s1, 24(a0)
    sd s2, 32(a0)
    sd s3, 40(a0)
    sd s4, 48(a0)
    sd s5, 56(a0)
    sd s6, 64(a0)
    sd s7, 72(a0)
    sd s8, 80(a0)
    sd s9, 88(a0)
    sd s10, 96(a0)
    sd s11, 104(a0)

    ld ra, 0(a1)
    ld sp, 8(a1)
    ld s0, 16(a1)
    ld s1, 24(a1)
    ld s2, 32(a1)
    ld s3, 40(a1)
    ld s4, 48(a1)
    ld s5, 56(a1)
    ld s6, 64(a1)
    ld s7, 72(a1)
    ld s8, 80(a1)
    ld s9, 88(a1)
    ld s10, 96(a1)
    ld s11, 104(a1)

	ret    /* return to ra */

Using threads

pthread_mutex_t locks[NBUCKET];
void init_locks()
{
	for (int i = 0; i < NBUCKET; i++)
	{
		pthread_mutex_init(&locks[i], NULL);
	}
}
static void put(int key, int value)
{
	int i = key % NBUCKET;
	// is the key already present?
	struct entry *e = 0;

	for (e = table[i]; e != 0; e = e->next)
	{
		if (e->key == key)
			break;
	}

	pthread_mutex_lock(&locks[i]);
	if (e)
	{
		// update the existing key.
		e->value = value;
	}
	else
	{
		// the new is new.
		insert(key, value, &table[i], table[i]);
	}
	pthread_mutex_unlock(&locks[i]);
}

 

Barrier

static void barrier()
{
	pthread_mutex_lock(&bstate.barrier_mutex);

	bstate.nthread++;
	if (bstate.nthread < nthread)
	{
		pthread_cond_wait(&bstate.barrier_cond, &bstate.barrier_mutex);
	}else
	{
		bstate.nthread = 0;
		bstate.round++;
		pthread_cond_broadcast(&bstate.barrier_cond);
	}

	pthread_mutex_unlock(&bstate.barrier_mutex);
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值