threadc语言
⑴ c语言多线程的操作步骤
线程创建
函数原型: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。
⑵ sleep()函数怎么具体在c语言中怎么用
Sleep方法是Java线程(Thread)开发中一种概念。是线程TIMED_WAITING状态中的一种方法。使用方法为:
1、类名为创建线程的类名。
注意事项:
Sleep函数可以使计算机程序(进程,任务或线程)进入休眠,使其在一段时间内处于非活动状态。当函数设定的计时器到期,或者接收到信号、程序发生中断都会导致程序继续执行。
⑶ c语言中多线程读写同一个环形缓冲区的实现
#include <stdio.h>
#include <windows.h>
#include <process.h>
unsigned __stdcall ThreadWrite(void* param);
unsigned __stdcall ThreadRead(void* param);
int WriteSeque = 0;
int ReadSeque = 0;
int RingBuf[4];
void main()
{
HANDLE htw = (HANDLE)_beginthreadex(NULL, 0, ThreadWrite, NULL, 0, 0);
HANDLE htr = (HANDLE)_beginthreadex(NULL, 0, ThreadRead, NULL, 0, 0);
CloseHandle(htw);
CloseHandle(htr);
while (1)
{
if (WriteSeque >= 100)
{
break;
}
}
printf("Quit\n");
}
unsigned __stdcall ThreadWrite(void* param)
{
int i = 0;
while (1)
{
if (WriteSeque >= ReadSeque && WriteSeque- ReadSeque < 4)
{
RingBuf[WriteSeque%4] = i;
printf("Write:%d\n", i);
i++;
WriteSeque++;
Sleep(50);
}
}
}
unsigned __stdcall ThreadRead(void* param)
{
while (1)
{
if (ReadSeque < WriteSeque)
{
printf("Read:%d\n", RingBuf[ReadSeque%4]);
ReadSeque++;
Sleep(100);
}
}
}
为了让你看到效果,读写线程的休眠时间略有不同。
⑷ C语言如何终止线程
有三种方式可以终止线程,具体调用函数依赖于使用的线程系统。
1 在线程入口函数中,调用return。 即退出线程入口函数,可以实现终止当前线程效果;
2 在线程执行的任意函数,调用当前线程退出函数,可以退出当前线程;
3 在任意位置,调用线程终止函数,并传入要终止线程的标识符,即pid,可以实现终止对应线程效果。