简体   繁体   English

与main()进行线程同步

[英]thread synchronization with main()

main()
{
    i=9000000000;      // to synchronize thread with while loop
    while(i)i--;      //if i don't use these two lines then my program terminates before thread starts.
    udp_socket();
    fun();
}

udp_socket()
{ 
    // open a udp socket then create thread
    pthread_create(tid1,NULL,fun2,(int *)socket_descriptor2);
}

fun()
{
}

fun2(int socket_descriptor2)
{
    while(1)
    {
    }
}
  1. i opened a UDP socket then create a thread ,inside thread a while loop is continuosly recieving data on the defined ip and port. 我打开了一个UDP套接字,然后创建了一个线程,在线程内部,while循环不断接收定义的ip和端口上的数据。

  2. My thread stop working when main terminates..... 当main终止时,我的线程停止工作.....

  3. i want to execute my thread continuously even when the main() terminates OR my main() also execute continuously without termination . 我想连续执行我的线程,即使main()终止,或者我的main()也连续执行而不终止。

how can i implement this? 我该如何实现呢?

If you don't want your main to terminate too early, make it at least waiting for thread termination. 如果您不希望main线程过早终止,请使其至少等待线程终止。 Suppose that you have tid1 accessible in your main, a simple call to pthread_join(tid1,NULL) will let the main thread waits. 假设您在主tid1可以访问pthread_join(tid1,NULL)pthread_join(tid1,NULL)的简单调用将使主线程等待。

In below example main waits for thread to complete ( fun2 to return). 在下面的示例中, main等待线程完成( fun2返回)。 fun2 returns when you enter an integer on stdin . 当您在stdinstdin整数时, fun2返回。

#include <stdio.h>
#include <pthread.h>

void fun() {
  printf("Hello from fun\n");
}

void fun2() {
  int a;
  scanf("%d", &a);
}

pthread_t udp_socket() {
  pthread_t tid;
  pthread_create(&tid,NULL,fun2,NULL);
  return tid;
}

int main() {
  void * ret = NULL;
  pthread_t t = udp_socket();
  fun();
  if(pthread_join(t, &ret)) {             // Waits for thread to terminate
    printf("Some Error Occurred\n");
  }
  else {
    printf("Successfully executed\n");
  }

Here is more information about pthread_join . 是有关pthread_join更多信息。

i want to execute my thread continuously even when the main() terminates 我想连续执行我的线程,即使main()终止

To do so exit int main() by calling pthread_exit() : 为此,通过调用pthread_exit()退出int main() pthread_exit()

int main(void)
{
  ...

  pthread_exit(NULL); /* This call exits main() and leaves all other thread running. */

  return 0; /* Is never reached, it's just there to silence the compiler. */
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM