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

主要用的线程函数:

1.创建线程:

1
2
intpthread_create(pthread_t *thread,constpthread_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);

执行结果:

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

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

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

执行结果:

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

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

现象分析:

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

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

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



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

上一篇:如何更有效的调试运行MATLAB程序(阅读)


下一篇:尝试更新了下suggest索引