C语言多线程的操作步骤

Python026

C语言多线程的操作步骤,第1张

线程创建

函数原型:intpthread_create(pthread_t*restrict tidp,const pthread_attr_t *restrict attr,void *(*start_rtn)(void),void *restrict arg)

返回值:若是成功建立线程返回0,否则返回错误的编号。

形式参数:pthread_t*restrict tidp要创建的线程的线程id指针;const pthread_attr_t *restrict attr创建线程时的线程属性;void *(start_rtn)(void)返回值是void类型的指针函数;void *restrict arg start_rtn的形参。

线程挂起:该函数的作用使得当前线程挂起,等待另一个线程返回才继续执行。也就是说当程序运行到这个地方时,程序会先停止,然后等线程id为thread的这个线程返回,然后程序才会断续执行。

函数原型:intpthread_join(pthread_tthread, void **value_ptr)

参数说明如下:thread等待退出线程的线程号;value_ptr退出线程的返回值。

返回值:若成功,则返回0;若失败,则返回错误号。

线程退出

函数原型:voidpthread_exit(void *rval_ptr)

获取当前线程id

函数原型:pthread_tpthread_self(void)

互斥锁

创建pthread_mutex_init;销毁pthread_mutex_destroy;加锁pthread_mutex_lock;解锁pthread_mutex_unlock。

条件锁

创建pthread_cond_init;销毁pthread_cond_destroy;触发pthread_cond_signal;广播pthread_cond_broadcast;等待pthread_cond_wait。

首先你要有控制蛇移动方向的全局变量(定义在main以外因为线程函数也要调用它,每次键盘输入都会修改它的值), 比如 char direction 'a' ==左 'w' == 右 'd'==上 's' == 下,然后你在移动时应该是在while里面操作的吧,你每移动一步前都读一下direction这个变量的数值然后再控制移动方向(注意s这个键可以忽略因为不会倒着走) 然后你可以用pthread.h这个库 例子是 pthread t// 定义一个线程 pthread_create(&t, null, listen_keyboard_input, null)//建立线程执行listen_keyboard_input这个函数 这个线程执行的函数 void listen_keyboard_input(){ while(应该通过某个信号来退出这个循环,从而表示游戏结束){direction =getchar() } } 但是这里存在同步问题, 比如当这个线程的getchar()在给direction辅助的同时,你控制贪吃蛇移动的线程正在调用 direction的值来判断下一个移动方向,这就会出问题,所以要加一个锁,叫 mutex lock这个也定义成全局变量可以使各线程共享。 pthread_mutex_t mutex//定义一个锁 pthread_mutex_init(&mutex, null, null)//初始化 然后把函数修改成 void listen_keyboard_input(){ while(应该通过某个信号来退出这个循环,从而表示游戏结束){pthread_mutex_lock(&mutex) direction =getchar() pthread_mutex_unlock(&mutex) } } 另外一个控制贪吃蛇移动的时候也要加锁 while(.....){ char c pthread_mutex_lock(&mutex) c = direction pthread_mutex_unlock(&mutex) switch(c){ ................ } ................................... } 这样就好了 注意你的控制贪吃蛇移动的部分也必须要放在另外一个pthread 里面执行,如果放在主线程, 主线程会一直等listen_keyboard_input而什么事都不会做 你把这两个线程用 pthread_create 创建完成后 用 t1.join() t2.join()就可以使这两个线程并发执行了 如果你用的是linux 来编译的,你再输入gcc 指令后加上 -lpthread 就可以了 还有什么不懂的你可以多找找 pthread 类的例子