linux C 编程题,求思路
1.有A,B两个线程,A线程每隔30秒给B线程发送时间到了的通知,B线程收到通知后作出响应并打印通知.求思路。...
1.有A ,B 两个线程,A线程每隔30秒给B线程发送时间到了的通知,B线程收到通知后作出响应并打印通知. 求思路。
展开
1个回答
展开全部
什么环境下,Linux可以消息队列、管道都行。
追问
ubuntu 我现在线程都建完了,就是不知道怎么通讯,管道和消息队列 通讯是什么机制
追答
这样吧我写一个最简单的例子给你吧。你要哪个哪个? 管道是Linux最传统的通讯机制,消息队列是基于SystemV通讯方法,其实按照你这样这个通讯的需求来看,应该通讯内容很简单,所以这里为了简单起见,我给一个管道通讯例子吧。
#include
#include
#include
#include
#include
#include
#include
//管道数组需要为全局变量,这样可以使线程在不同模块之间通讯
//或者使用命名管道或向线程传递参数,方式很多,自己选择。
int pipe_fd[2];
//两个线程id
pthread_t thread1;
pthread_t thread2;
//第一个线程的主体函数:定时发送消息给线程2
void * thread1_func(void * args)
{
int ret;
int i = 0;
char msg[128];
while(1)
{
sprintf(msg,"Number = %d",i++);
ret = write(pipe_fd[1],msg,strlen(msg));
sleep(1);
}
return (void *)0;}
//第二个线程的主体函数:收到消息后打印出来。
void * thread2_func(void * args)
{
int ret;
char buffer[128];
while(1)
{
memset(buffer,0,128);
ret = read(pipe_fd[0],buffer,128);
printf("Rec Msg = %s \n", buffer);
}
}
int init_thread(void)
{
int ret;
ret = pthread_create(&thread1,
NULL,
(void *)thread1_func,
NULL
);
if(ret)
{
perror("thread1 fail\n");
return -1;
}
ret = pthread_create(&thread2,
NULL,
(void *)thread2_func,
NULL
);
if(ret)
{
perror("thread2 fail\n");
return -1;
}
}
int main(int argn , char ** argv)
{
char cmd[32];
if(pipe(pipe_fd)== 0 )
{
init_thread();
}
else
{
printf("pipe error\n");
return -1;
}
sleep(1000);
return 0;
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询