【发布时间】:2021-08-18 23:20:32
【问题描述】:
我有一个 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, 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 创建另一个线程?
【问题讨论】:
-
您是否使用任何互斥锁来控制对两个线程读取/写入的变量的访问?
-
@dbush 是的,我是为队列做的,而且两个线程没有共同的变量
-
发布的代码没有显示。另外,主线程和发送者线程使用
queue_hndl,没有互斥体。 -
join的语义是等待加入的线程完成。所以如果你立即加入,你的主线程当然会被阻塞。你确实应该加入,但不是在工作线程确实打算终止之前,所以你会在 main 内的 while 循环之后这样做。
标签: c multithreading pthreads cygwin