Linux C 多线程互斥锁及线程同步问题 (二)

需求:主线程创建子线程后等待子线程真正运行。然后主线程向子线程发送同步请求,保证主线程的同步请求信号不丢失。

测试代码:(来自百度,修改。。。)

#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才稳定下来。(蓝色)

猜想,提高子线程的优先级可能会解决。等待下次实验吧。




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值