Gdzie jest błąd klasa z thread zle wyświetlającza wartości
Ostatnio zmodyfikowano 2017-09-28 17:15
Breakermind Temat założony przez niniejszego użytkownika |
Gdzie jest błąd klasa z thread zle wyświetlającza wartości » 2017-09-28 12:06:18 Witam worker_thread źle wyświetla wartości, gdzie zrobiłem błąd i jak go poprawić (chcę uruchamiać treda z klasy i przekazać do niego jakaś strukturę): // sendmailthreads.cpp #include "sendemailthreads.h"
SendEmailThreads::SendEmailThreads( int id ) { thread_info tinfo; tinfo.client = id; tinfo.ctx = id; tinfo.th_id = id; int ret = pthread_create( & thread, NULL, & worker_thread, & tinfo ); if( ret != 0 ) { cout << "Error: pthread_create() failed " << "\n "; exit( EXIT_FAILURE ); } else { cout << "In main: creating thread " << " \n"; } if( ret > 0 ) { fprintf( stderr, "Mam mowego klienta, pid=%d\n", ret ); } if( ret < 0 ) { perror( "Unable to accept" ); exit( EXIT_FAILURE ); } }
bool SendEmailThreads::SaveToFile( string filename, string text ) { try { std::ofstream outfile; mkdir( "files", S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH ); outfile.open( "files/" + filename + ".log", std::ios_base::app ); outfile << text << endl; outfile.close(); return 1; } catch( const std::exception & exc ) { return 0; } }
void * SendEmailThreads::worker_thread( void * arg ) { thread_info * tinfo =( thread_info * ) arg; while( 1 ) { time_t seconds = time( NULL ); SaveToFile( "thread", "Thread " + std::to_string(( int ) tinfo->client ) + " time " + std::to_string(( int ) seconds ) ); usleep( 1000000 ); } pthread_exit( NULL ); }
struct SendEmailThreads::thread_info;
pthread_t SendEmailThreads::thread;
sendmailthreads.h #ifndef SENDEMAILTHREADS_H #define SENDEMAILTHREADS_H
#include <string>
#include <pthread.h>
#include <time.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fstream>
#include <iostream>
using namespace std;
class SendEmailThreads { public: SendEmailThreads( int id ); static pthread_t thread; static bool SaveToFile( string filename, string text ); static void * worker_thread( void * arg ); struct thread_info { int th_id; int ctx; int client; }; };
#endif
Uruchamiam: SendEmailThreads t1 = SendEmailThreads(5); Pozdrawiam |
|
Monika90 |
» 2017-09-28 12:31:28 tinfo to zmienna lokalna więc po wyjściu z konstruktora nie istnieje, a wątek próbuje jej używać przez wskaźnik.
Najlepiej użyj C++. |
|
Breakermind Temat założony przez niniejszego użytkownika |
» 2017-09-28 17:15:24 Dzięki, faktycznie nie dodałem deklaracji w klasie a tylko strukturę :). To tak jak się za dużo rzeczy na raz robi :D. Tak właśnie czułem że to Monika90 napisze ;) Pozdrawiam :x |
|
« 1 » |