Example: Thread

From Miosix Wiki
Revision as of 21:12, 13 April 2014 by Andreabont (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

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