Skip to content

CPP Ejemplo de I O

Richard T. Miles edited this page Aug 22, 2017 · 3 revisions

C++ & Pthreads

*** Here is a good example of threading written in c++. You are welcome to use this code, but keep the first comment ;)

To compile should compile using

g++ -lpthread main.cpp

main.cpp

-- lil'Richard
#include <iostream>
#include <stdio.h>

#define TCOUNT 10
#define WCOUNT 12

int count = 0;
char buffer[225];

pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t  c = PTHREAD_COND_INITIALIZER;

void *output(void *idp)
{
    int passed_in_value = *((int *) idp);

    pthread_mutex_lock(&m);

    while (count <= WCOUNT)
    {
        pthread_cond_wait(&c, &m);
        printf("watch_count(): Thread %d, Count %d, Buffer: %s  \n", passed_in_value, count, buffer);
    }

    pthread_mutex_unlock(&m);
}

void *inc_count(void *idp)
{
    int i;

    int passed_in_value = *((int *) idp);

    for (i = 0; i < TCOUNT; i++)
    {
        count++;
        pthread_mutex_lock(&m);
        printf("inc_count(): Thread %d, old count %d, new count %d\n", passed_in_value, count - 1, count);
        if (count == WCOUNT)
        {
            scanf("%s",buffer);
            printf("Thread %d signaled :: Read) %s \n", passed_in_value, buffer);
            pthread_cond_signal(&c);
        }

        pthread_mutex_unlock(&m);
    }
}

int main()
{
    int i, tids[3] = {0, 1, 2};
    pthread_t threads[3];

    pthread_cond_init(&c, NULL);

    pthread_create(&threads[0], NULL, inc_count, (void *) &tids[0]);
    pthread_create(&threads[1], NULL, inc_count, (void *) &tids[1]);
    pthread_create(&threads[2], NULL, output, (void *) &tids[2]);

    for (i = 0; i < 3; i++) {
        pthread_join(threads[i], NULL);
    }
    pthread_mutex_destroy(&m);
    pthread_cond_destroy(&c);
    return 0;
}

C++0x

El ejemplo está todavía en desarrollo por Roboticus, no se recomienda utilizar todavía.

example.cpp

#include <stdio.h>
#include <unistd.h>
#include <iostream>
#include <string>
#include <thread>
#include <mutex>

using namespace std;

mutex m;
string *msg;

void in()
{
    while(true)
	{
		for (string line; getline(cin, line);)
		{
		    m.lock();
		    msg = new string("RCVD: ");
		    *msg += line;
		    m.unlock();
		}
	}
}

void out()
{
    while(true)
    {
        m.lock();
        if (msg)
        {
            cout << "You sent me: " << *msg << endl;
            msg = 0;
        }
        m.unlock();
        usleep(1000000);
    }
}

int main() {
    // Disable input/output buffering.
    setbuf(stdout, NULL);
    setbuf(stdin, NULL);

    thread inThread(in);
    thread outThread(out);

    inThread.join();
    outThread.join();

    return 0;
}

Compilar con:

g++ -pthread -std=c++0x example.cpp -o example

En MacOSX, Roboticus usa:

clang -pthread -std=c++0x example.cpp -o example -lstdc++

Ejecutar de esta manera:

./websocketd -port=8080 --staticdir=. ./example

C++11

#include <iostream>
#include <mutex>
#include <string>
#include <thread>

std::mutex msg_mutex;
std::string msg;

void read()
{
  while (true) {
    std::string sin;
    std::cin >> sin;
    std::lock_guard<std::mutex> lock{msg_mutex};
    msg = sin;
  }
}

void write()
{
  while (true) {
    std::lock_guard<std::mutex> lock{msg_mutex};
    if (msg.length() > 0) {
      std::cout << msg << std::endl;
      msg.clear();
    }
  }
}

int main()
{
  std::thread reader(read);
  std::thread writer(write);

  reader.join();
  writer.join();
  return 0;
}

Compilar con:

clang++ -std=c++11 -pthread -o example example.cpp

Ejecutar con:

./websocketd --port=8080 ./example

Interacción.

Interactuar a través de la siguiente página web:

<!DOCTYPE html>
<html>
    <head>
        <title>Simple C++ I/O Example</title>
        <script>
            var ws = new WebSocket('ws://127.0.0.1:8080/');

            ws.onmessage = function(event) {
                document.getElementById('msgBox').innerHTML = event.data;
                document.getElementById('outMsg').value='';
            }
            
            function send()
            {
                ws.send(document.getElementById('outMsg').value);
            }
        </script>
    </head>
    <body>
        <div id='msgBox'>Nothing sent yet!</div>
        <input type="text" id="outMsg">
        <button type="button" onclick="send()">Send</button>
    </body>
</html>
Clone this wiki locally