天天看点

多线程本地图片加载示例【OpenCV】【Pthread】

Pthread barrier的简单使用示例:

C++代码如下:

// ThreadingLoadImages.cpp : 定义控制台应用程序的入口点。
//
 
#include "stdafx.h"
#include <pthread.h>
#include <opencv2/opencv.hpp>
 
#define THREADS 3
 
// Barrier variable
pthread_barrier_t barr;
 
 
struct Param
{
    cv::Mat img;
    int index;
    char* file_path;
} params[THREADS];
 
void* entry_point(void* arg)
{
    Param* p = (Param*)arg;
    
    int index = p->index;
    char* file_path = p->file_path;
 
    p->img = cv::imread(file_path);
 
    printf("The %d thread is doing job! \n", index);
 
    // Synchronization point
    int rc = pthread_barrier_wait(&barr);
    if (rc != 0 && rc != PTHREAD_BARRIER_SERIAL_THREAD)
    {
        printf("Could not wait on barrier\n");
        exit(-1);
    }
}
 
 
int main()
{
    pthread_t thr[THREADS];
    //pthread_mutex_init(&g_mtx, NULL);
 
    // Barrier initialization
    if (pthread_barrier_init(&barr, NULL, THREADS))
    {
        printf("Could not create a barrier\n");
        return -1;
    }
 
    //int t[THREADS];
    params[0].file_path = "../micky.png";
    params[1].file_path = "../umbrella.png";
    params[2].file_path = "../beard.jpg";
 
    for (int i = 0; i < THREADS; ++i)
    {
        //t[i] = i;
        params[i].index = i;
    
        if (pthread_create(&thr[i], NULL, &entry_point, (void *)&params[i]))
        {
            printf("Could not create thread %d\n", i);
            return -1;
        }
    }
 
    for (int i = 0; i < THREADS; ++i)
    {
        if (pthread_join(thr[i], NULL))
        {
            printf("Could not join thread %d\n", i);
            return -1;
        }
    }
    printf("All threads finish jobs! \n");
 
    for(int i=0; i<THREADS; i++)
        cv::imshow(params[i].file_path, params[i].img);
    cv::waitKey(0);
 
    return 0;
}      

效果如图:

多线程本地图片加载示例【OpenCV】【Pthread】

相关资料:

pthread线程使用小结

继续阅读