如何解决如何让我的主线程和 p 线程保持活动状态?
我有一个 main 函数,它有一个 while 循环,它使我的程序保持活动状态,但是当我调用另一个线程(这是必需的)时,我的主线程退出,或者我必须通过调用 thread join 来挂起它,我不知道是不是我的代码问题
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,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,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;
}
>>>>>>Sender_Engine_Started<<<<<<<
0 [main] nwudp 1647 cygwin_exception::open_stackdumpfile: Dumping stack trace to
nwudp.exe.stackdump
.
当我取消注释 pthread join 时,我的线程(Sender_thread)运行良好,但我的主线程中的 while 循环停止
我怎样才能让两者都活着?还是应该为 main 创建另一个线程?
解决方法
我已经解决了这个问题,我的队列句柄“queue_hndl”在初始化之前在主循环中使用,它在我的线程开始之前被初始化,所以我在开始我的线程之前改变了它获取句柄现在它可以工作了
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。