需求:主线程创建子线程后等待子线程真正运行。然后主线程向子线程发送同步请求,保证主线程的同步请求信号不丢失。
测试代码:(来自百度,修改。。。)
#include <sys/time.h>
#include <pthread.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
static int count = 0;
struct timeval tv1,tv2,tv3;
int timestamp1,timestamp2,timestamp3;
/*释放节点内存 */
static void cleanup_handler(void *arg)
{
printf("Cleanup handler of second thread.\n");
free(arg);
(void)pthread_mutex_unlock(&mtx);
}
static void *thread_func(void *arg)
{
int time_fun=0;
printf("try lock10........\n");
pthread_mutex_lock(&mtx);
printf("locked10........\n");
pthread_cond_signal(&cond);
printf("sended msg to main........\n");
pthread_mutex_unlock(&mtx); //解锁
while (1)
{
printf("wait msg from mian................\n");
pthread_cond_wait(&cond, &mtx);
printf("get msg from mian.....count:%d.....\n",count);
}
return 0;
}
int main(void)
{
int time_create=0;
pthread_t tid;
int i;
pthread_mutexattr_t mutex_attr;
pthread_condattr_t cond_attr;
pthread_mutexattr_init(&mutex_attr);
pthread_condattr_init(&cond_attr);
pthread_mutex_init(&mtx, &mutex_attr);
pthread_cond_init(&cond, &cond_attr);
pthread_condattr_destroy(&cond_attr);
pthread_mutexattr_destroy(&mutex_attr);
gettimeofday(&tv1, NULL);
timestamp1 = tv1.tv_sec * 1000 * 1000 + tv1.tv_usec;
pthread_create(&tid, NULL, thread_func, NULL);
printf("try lock00...........\n");
pthread_mutex_lock(&mtx);
printf("locked00...waiting msg from son.......\n");
pthread_cond_wait(&cond, &mtx);
printf("recved msg from son.......\n");
pthread_mutex_unlock(&mtx); //解锁
//usleep(1000);
for (i = 0; i < 10; i++)
{
printf("try lock 02.........\n");
pthread_mutex_lock(&mtx); //需要操作head这个临界资源,先加锁,
printf("locked 02.........\n");
count = i;
pthread_cond_signal(&cond);
printf("try unlock 02.........\n");
pthread_mutex_unlock(&mtx); //解锁
printf("unlocked 02.........\n");
sleep(1);
}
printf("thread 1 wanna end the cancel thread 2.\n");
pthread_cancel(tid);
pthread_join(tid, NULL);
printf("All done -- exiting\n");
return 0;
}
猜想,主线程创建子线后阻塞等待子线程同步请求,应该可以达到我的需求,事实是第一个主线程的同步请求仍然丢失(偶尔不会丢失)。
暂时就只有休眠等待了修时间增加到1ms才稳定下来。(蓝色)
猜想,提高子线程的优先级可能会解决。等待下次实验吧。