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

10 篇文章 0 订阅

主要用的线程函数:

1.创建线程:

1
2
int pthread_create(pthread_t * thread , const pthread_attr_t *attr,
                    void *(*start_routine) ( void *), void *arg);

测试代码:代码来自百度 稍作修改
测试平台:ARM

#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;
   // pthread_cleanup_push(cleanup_handler, p);

    gettimeofday(&tv3, NULL);
    timestamp3 = tv3.tv_sec * 1000 * 1000 + tv3.tv_usec;
    time_fun = timestamp3 - timestamp1;
    printf("time_fun:%d\n",time_fun);

    while (1)
    {
        pthread_mutex_lock(&mtx);
 
        while (1)
        {
            pthread_cond_wait(&cond, &mtx);

            printf("Got %d from front of queue\n",count);

        }
        pthread_mutex_unlock(&mtx); //临界区数据操作完毕,释放互斥锁

    }

   // pthread_cleanup_pop(0);
    return 0;
}

int main(void)
{
	int time_create=0;
    pthread_t tid;
    int i;
    gettimeofday(&tv1, NULL);
    timestamp1 = tv1.tv_sec * 1000 * 1000 + tv1.tv_usec;

    pthread_create(&tid, NULL, thread_func, NULL);

    gettimeofday(&tv2, NULL);
    timestamp2 = tv2.tv_sec * 1000 * 1000 + tv2.tv_usec;
    time_create = timestamp2 - timestamp1;
    printf("time_create:%d\n",time_create);
  
    //usleep(10000);
    for (i = 0; i < 10; i++)
    {

        pthread_mutex_lock(&mtx); //需要操作head这个临界资源,先加锁,
        count = i;
        pthread_cond_signal(&cond);
        pthread_mutex_unlock(&mtx); //解锁
        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;
}

测试1 注释掉:   //usleep(10000);

执行结果:



测试2:取消 注释掉:   usleep(10000);

执行结果:




现象分析:

pthread_create(&tid, NULL, thread_func, NULL);
这个语句的执行时间在2000us 到5000us之间

而 正真线程创建到线程函数体的执行时间大于5000us

所以第一次主线程发送同步信号的时候,子线程还没有启动完成造成测试1的第一个同步信息丢失。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值