c - 如何保持我的主线程和 p 线程活着?
问题描述
我有一个 main 函数,它有一个 while 循环,可以让我的程序保持活动状态,但是当我调用另一个线程(这是必需的)时,我的主线程退出或者我必须通过调用线程连接来挂起它,我不知道是否这是我的代码问题
我有一个调用我的线程的函数
int start_sender_engine(void)
{
thread1_ret = pthread_create(&Send_thread_1, NULL, Sender_thread,(void*) message1);
//pthread_join(Send_thread_1, NULL);
return 0;
}
我在这里调用这个线程,
现在我的主线程是这样的
int main (int argc, char *argv[])
{
start_sender_engine();
while(1)
{
data.CommandCode=33+cont[0];
data.DataSize=sizeof(cont);
data.Data=cont;
Enqueue_elements(queue_hndl, &data);
usleep(1000*1000);
}
deleteQueue(queue_hndl);
}
我的出队函数位于线程内
void *Sender_thread(void *msg_ptr) // Sender Engine
{
char *message;
message = (char *) msg_ptr;
printf("%s\n",message);
fflush(stdout);
/*
* Create a datagram socket on which to send.
*/
sd = socket(AF_INET, SOCK_DGRAM, 0);
if (sd < 0) {
perror("opening datagram socket");
exit(1);
}
/*
* Initialize the group sockaddr structure with a
* group address of 225.1.1.1 and port 5555.
*/
memset((char *) &groupSock, 0, sizeof(groupSock));
groupSock.sin_family = AF_INET;
groupSock.sin_addr.s_addr = inet_addr("225.1.1.2");
groupSock.sin_port = htons(65533);
/*
* Disable loopback so you do not receive your own datagrams.
*/
{
char loopch=0;
if (setsockopt(sd, IPPROTO_IP, IP_MULTICAST_LOOP,
(char *)&loopch, sizeof(loopch)) < 0) {
perror("setting IP_MULTICAST_LOOP:");
close(sd);
exit(1);
}
}
/*
* Set local interface for outbound multicast datagrams.
* The IP address specified must be associated with a local,
* multicast-capable interface.
*/
localInterface.s_addr = inet_addr("192.168.1.10");
if (setsockopt(sd, IPPROTO_IP, IP_MULTICAST_IF,
(char *)&localInterface,
sizeof(localInterface)) < 0) {
perror("setting local interface");
exit(1);
}
/*
* Send a message to the multicast group specified by the
* groupSock sockaddr structure.
*/
//// Queue ////////
queue_hndl = createQueue(1000, (sizeof(SenderData) + 5000) );
while(stop_nw_global!=1)
{
if(no_elements(queue_hndl)>0)
{
temp=Dequeue_elements(queue_hndl);
printf("CMD Code %d",temp->CommandCode);
printf("---Size %d",temp->DataSize);
int *testi = (int*)temp->Data;
printf("Sending- %d\n", testi[0]);
fflush(stdout);
send_packets(*temp,100);
}
else
{
usleep(1000*1000);
printf(".\n");
fflush(stdout);
}
}
return 0;
}
当我评论 pthread join 时,我收到一条错误消息
>>>>>>Sender_Engine_Started<<<<<<<
0 [main] nwudp 1647 cygwin_exception::open_stackdumpfile: Dumping stack trace to
nwudp.exe.stackdump
.
当我取消评论 pthread 加入时,我的线程(Sender_thread)工作得很好,但是我的 main 内的 while 循环停止了
我怎样才能让两者都活着?还是我应该为main创建另一个线程?
解决方案
我已经解决了这个问题,我的队列句柄“queue_hndl”在它被初始化之前在主循环中使用,它在我的线程开始之前被初始化,所以我在启动我的线程之前更改了它获取句柄,现在它作品
推荐阅读
- python - 验证字符串输入并将其连接到列表
- react-native - 将数据从一更新到。另一个屏幕
- asp.net-web-api - 在 NetCore 2.1 中同步 Apple 日历
- ignite - 在 Apache Ignite 中加入查询
- java - 如何防止在java mysql中将重复数据插入数据库
- r - 编织 RMarkdown 文档时出现 YAML 错误 - 扫描仪错误
- linq - 如何在 linq 中与运营商一起使用英国格式的日期
- zend-framework - 如何为 SocialEngine 模块设置默认操作
- c# - 将 2 层架构转换为 3 层架构
- java - org.javalite.activejdbc.DBException:在环境属性文件中找不到配置:开发