简单的pthread C程序-同步问题



我得到了这个使用pthreads的简单C程序。

我基本上想在100%确定my_thread()被调用并被执行后调用my_function()

我需要知道如何同步main()函数和my_thread()函数。

请注意,my_thread()永远不会返回。

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

void  my_function (void);
void* my_thread (void* arg);

int main (int argc, char* argv[])
{
int rc;
pthread_t id;

rc = pthread_create(&id, NULL, my_thread, NULL);
if (rc != 0)
{
return -10;
}


/*
* I wanna call my_function() once I'm 100% sure my_thread() gets called and being executed
*/

/*
* Synchronization code to add here:
*/     


my_function();


return 0;
}

void* my_thread (void* arg)
{

/*
* This pthread never returns
*/

while (1)
{
/* stuff */
};

}
void my_function (void)
{
printf("Hellon");
}

谢谢你的帮助。

有人能检查这个解决方案是否正确吗?

它使用调试器工作,但我想听听有经验的程序员的意见。

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

void  my_function (void);
void* my_thread (void* arg);
int started;
pthread_mutex_t mutex;   
pthread_t id;
int main (int argc, char* argv[])
{
int rc;
int done;       

started = 0;
mutex = PTHREAD_MUTEX_INITIALIZER;

rc = pthread_create(&id, NULL, my_thread, NULL);
if (rc != 0)
{
return -10;
}


/*
* Synchronization code proposed:
*/             
done = 0;
do
{

pthread_mutex_lock(&mutex);
if (started == 1)
{
done = 1;
}
pthread_mutex_unlock(&mutex);

} 
while (done == 0);


/*
* I wanna call my_function() once I'm 100% sure
* that my_thread() is called and being executed
*/
my_function();


return 0;
}

void* my_thread (void* arg)
{

started = 1;

while (1)
{
/* stuff */
};

}
void  my_function (void)
{
printf("Hellon");
}

相关内容

  • 没有找到相关文章

最新更新