在驱动代码中会很普遍的用到pthread,workqueue等方法。
pthread常用的方法有:
pthread_mutex_init,pthread_mutex_destroy
pthread_cond_init,pthread_cond_destroy
pthread_create,pthread_exit
pthread_mutex_lock,pthread_mutex_unlock
pthread_cond_wait,pthread_cond_signal
具体的使用参考下面代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#define END "0"
enum THREAD_STATE
{
WORKING,
EXITING,
};
static enum THREAD_STATE thread_state = WORKING;
static pthread_mutex_t plock;
static pthread_cond_t pwait;
static char buf[128];
static pthread_t pthread_t1;
static void *thread1(void)
{
while(1)
{
pthread_mutex_lock(&plock); //取得互斥锁,确保下一步的操作是安全的,不会被打断的
pthread_cond_wait(&pwait, &plock); //阻塞在此,等待主线程发送信号量解除阻塞
if(thread_state == EXITING)
break;
printf("your input is %s\n", buf);
memset(buf, 0, sizeof(buf));
pthread_mutex_unlock(&plock); //操作完成释放互斥锁
}
pthread_exit(NULL); //退出线程
}
static void init(void)
{
pthread_mutex_init(&plock, NULL); //初始化互斥锁 NULL表示使用默认参数
pthread_cond_init(&pwait, NULL); //初始化信号量
printf("init success.\n");
}
static void run_thread(void)
{
int ret = -1;
ret = pthread_create(&pthread_t1, NULL, (void *)thread1, NULL); //创建子线程
if(ret != 0)
exit(-1);
printf("run thread success.\n");
}
static void wait_input(void)
{
memset(buf, 0, sizeof(buf));
while(1)
{
scanf("%s", buf); //阻塞,等待键盘输入
if(strcmp(buf, END) == 0)
{
thread_state = EXITING; //如果输入0,改变状态,结束程序
pthread_cond_signal(&pwait); //发送信号量给子线程,解除子线程的阻塞
return;
}
pthread_cond_signal(&pwait); //发送信号量给子线程,解除子线程的阻塞
}
}
static void release(void)
{
int ret = -1;
ret = pthread_join(pthread_t1, NULL); //等待子线程结束
if(ret != 0)
{
printf("pthread_join error =%d\n", ret);
}
pthread_mutex_destroy(&plock); //释放相关的资源
pthread_cond_destroy(&pwait);
printf("release success.\n");
}
int main(int argc, char const *argv[])
{
init();
run_thread();
wait_input();
release();
return 0;
}