Example: Thread

From Miosix Wiki
Revision as of 21:10, 13 April 2014 by Andreabont (talk | contribs) (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...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

Native

//
// To build this example modify the Makefile so that
// SRC := native_thread_example.cpp
//

#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

//
// To build this example modify the Makefile so that
// SRC := pthread_example.cpp
//

#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);
}