Example: Thread: Difference between revisions

From Miosix Wiki
Jump to navigation Jump to search
(Created page with "=== Native === <source lang="cpp"> // // To build this example modify the Makefile so that // SRC := native_thread_example.cpp // #include <stdio.h> #include <string.h> #incl...")
 
No edit summary
 
Line 1: Line 1:
=== Native ===
=== Native ===
<source lang="cpp">
<source lang="cpp">
//
// To build this example modify the Makefile so that
// SRC := native_thread_example.cpp
//
#include <stdio.h>
#include <stdio.h>
#include <string.h>
#include <string.h>
Line 48: Line 43:
=== Pthread ===
=== Pthread ===
<source lang="cpp">
<source lang="cpp">
//
// To build this example modify the Makefile so that
// SRC := pthread_example.cpp
//
#include <stdio.h>
#include <stdio.h>
#include <string.h>
#include <string.h>

Latest revision as of 21:12, 13 April 2014

Native

#include <stdio.h>
#include <string.h>
#include "miosix.h"

using namespace miosix;

Mutex mutex;
ConditionVariable cond,ack;
char c=0;

void threadfunc(void *argv)
{
    Lock<Mutex> lock(mutex);
    for(int i=0;i<(int)argv;i++)
    {
        ack.signal();
        while(c==0) cond.wait(lock);
        printf("%c",c);
        c=0;
    }
}

int main()
{
    const char str[]="Hello world\n";
    Thread *thread;
    thread=Thread::create(threadfunc,2048,1,(void*)strlen(str),Thread::JOINABLE);
    {
        Lock<Mutex> lock(mutex);
        for(int i=0;i<strlen(str);i++)
        {
            c=str[i];
            cond.signal();
            if(i<strlen(str)-1) ack.wait(lock);
        }
    }
    thread->join();
}

Pthread

#include <stdio.h>
#include <string.h>
#include <pthread.h>

pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond=PTHREAD_COND_INITIALIZER;
pthread_cond_t ack=PTHREAD_COND_INITIALIZER;
char c=0;

void *threadfunc(void *argv)
{
    pthread_mutex_lock(&mutex);
    for(int i=0;i<(int)argv;i++)
    {
        pthread_cond_signal(&ack);
        while(c==0) pthread_cond_wait(&cond,&mutex);
        printf("%c",c);
        c=0;
    }
    pthread_mutex_unlock(&mutex);
}

int main()
{
    getchar();
    const char str[]="Hello world\n";
    pthread_t thread;
    pthread_create(&thread,NULL,threadfunc,(void*)strlen(str));
    pthread_mutex_lock(&mutex);
    for(int i=0;i<strlen(str);i++)
    {
        c=str[i];
        pthread_cond_signal(&cond);
        if(i<strlen(str)-1) pthread_cond_wait(&ack,&mutex);
    }
    pthread_mutex_unlock(&mutex);
    pthread_join(thread,NULL);
}