La funzione principale è basata su libevent, ma nella funzione esiste un'attività a lungo termine. Quindi, avvia N per eseguire le attività. Questa idea è OK? E come usare libevent e pthread insieme in C?Come utilizzare libevent e pthread insieme in C
risposta
Ciò funzionerebbe.
Nella funzione di callback I/O delega il lavoro che richiede molto tempo a un altro thread di un pool di thread. La meccanica esatta dipende dall'interfaccia del thread di lavoro o dal pool di thread.
Per comunicare il risultato dal thread di lavoro al thread di I/O, utilizzare una pipe. Il thread di lavoro scrive il puntatore sull'oggetto risultato nella pipe e il thread I/O si riattiva e legge il puntatore dalla pipe.
C'è un esempio libevent multithread in questo post del blog: http://www.roncemer.com/multi-threaded-libevent-server-example
sua soluzione è, per citare:
La soluzione è quella di creare una coda di eventi libevent (AKA Event_Base) per connessione attiva , ciascuno con il proprio thread della pompa di eventi. Questo progetto fa esattamente questo, dandoti tutto il necessario per scrivere server socket ad alte prestazioni, multi-threaded, libevent.
Collegamento interrotto o forse il server è inattivo. Si prega di copiare e incollare il codice in aggiunta agli URL piuttosto che fornire solo i collegamenti. – enthusiasticgeek
@enthusiasticgeek, Il server è attivo e una ricerca sul suo blog non mostra post su libevent, quindi forse ha trovato un difetto e ha appena cancellato il post. Ecco un'istantanea della pagina dal 2012: http://web.archive.org/web/20120707080222/http://www.roncemer.com/multi-threaded-libevent-server-example Ecco il progetto sourceforge collegato- a dall'istantanea: http://sourceforge.net/projects/libevent-thread/ Non ho guardato questo per un po ', ma siete invitati a tagliare e incollare qualche codice da soli se avete la testa nel problema adesso . – ahcox
Grazie per i collegamenti! – enthusiasticgeek
NOTA Questo è per libev not libevent ma l'idea potrebbe essere applicata.
Qui presento un esempio per la comunità. Si prega di commentare e fammi sapere se ci sono alcuni bug evidenti. Questo esempio potrebbe includere un gestore di segnale per la terminazione del thread e l'uscita aggraziata in futuro.
//This program is demo for using pthreads with libev.
//Try using Timeout values as large as 1.0 and as small as 0.000001
//and notice the difference in the output
//(c) 2009 debuguo
//(c) 2013 enthusiasticgeek for stack overflow
//Free to distribute and improve the code. Leave credits intact
//compile using: gcc -g test.c -o test -lpthread -lev
#include <ev.h>
#include <stdio.h> // for puts
#include <stdlib.h>
#include <pthread.h>
pthread_mutex_t lock;
double timeout = 0.00001;
ev_timer timeout_watcher;
int timeout_count = 0;
ev_async async_watcher;
int async_count = 0;
struct ev_loop* loop2;
void* loop2thread(void* args)
{
// now wait for events to arrive on the inner loop
ev_loop(loop2, 0);
return NULL;
}
static void async_cb (EV_P_ ev_async *w, int revents)
{
//puts ("async ready");
pthread_mutex_lock(&lock); //Don't forget locking
++async_count;
printf("async = %d, timeout = %d \n", async_count, timeout_count);
pthread_mutex_unlock(&lock); //Don't forget unlocking
}
static void timeout_cb (EV_P_ ev_timer *w, int revents) // Timer callback function
{
//puts ("timeout");
if(ev_async_pending(&async_watcher)==false){ //the event has not yet been processed (or even noted) by the event loop? (i.e. Is it serviced? If yes then proceed to)
ev_async_send(loop2, &async_watcher); //Sends/signals/activates the given ev_async watcher, that is, feeds an EV_ASYNC event on the watcher into the event loop.
}
pthread_mutex_lock(&lock); //Don't forget locking
++timeout_count;
pthread_mutex_unlock(&lock); //Don't forget unlocking
w->repeat = timeout;
ev_timer_again(loop, &timeout_watcher); //Start the timer again.
}
int main (int argc, char** argv)
{
if (argc < 2) {
puts("Timeout value missing.\n./demo <timeout>");
return -1;
}
timeout = atof(argv[1]);
struct ev_loop *loop = EV_DEFAULT; //or ev_default_loop (0);
//Initialize pthread
pthread_mutex_init(&lock, NULL);
pthread_t thread;
// This loop sits in the pthread
loop2 = ev_loop_new(0);
//This block is specifically used pre-empting thread (i.e. temporary interruption and suspension of a task, without asking for its cooperation, with the intention to resume that task later.)
//This takes into account thread safety
ev_async_init(&async_watcher, async_cb);
ev_async_start(loop2, &async_watcher);
pthread_create(&thread, NULL, loop2thread, NULL);
ev_timer_init (&timeout_watcher, timeout_cb, timeout, 0.); // Non repeating timer. The timer starts repeating in the timeout callback function
ev_timer_start (loop, &timeout_watcher);
// now wait for events to arrive on the main loop
ev_loop(loop, 0);
//Wait on threads for execution
pthread_join(thread, NULL);
pthread_mutex_destroy(&lock);
return 0;
}
Urtando una vecchia questione, potrebbe essere già stato risolto. Ma postare la risposta nel caso in cui qualcun altro ne avesse bisogno.
Sì, in questo caso è possibile eseguire il threading. Recentemente ho usato libevent in pthreads, e sembra che stia funzionando bene. Ecco il codice:
#include <stdint.h>
#include <pthread.h>
#include <event.h>
void * thread_func (void *);
int main(void)
{
int32_t tid = 0, ret = -1;
struct event_base *evbase;
struct event *ev;
int32_t *t_ret = &ret;
struct timeval tv;
// 1. initialize libevent for pthreads
evthread_use_pthreads();
ret = pthread_create(&tid, NULL, thread_func, NULL);
// check ret for error
// 2. allocate event base
evbase = event_base_new();
// 3. allocate event object
timer = event_new(evbase, -1, EV_PERSIST, callback_func, NULL);
// 4. add event
tv.tv_sec = 0;
tv.tv_usec = 1000;
evtimer_add(timer, &tv);
// 5. start the event loop
event_base_dispatch(evbase); // event loop
// join pthread...
// 6. free resources
event_free(timer);
event_base_free(evbase);
return 0;
}
void * thread_func(void *arg)
{
struct event *ev;
struct event_base *base;
base = event_base_new();
ev = event_new(base, -1, EV_PERSIST, thread_callback, NULL);
event_add(ev, NULL); // wait forever
event_base_dispatch(base); // start event loop
event_free(ev);
event_base_free(base);
pthread_exit(0);
}
Come si può vedere, nel mio caso, l'evento per il thread principale è il timer. La logica di base seguito è la seguente:
- chiamata evthread_use_pthreads() per inizializzare libevent per pthreads su Linux (il mio caso). Per windows evthread_use_window_threads(). Controlla la documentazione fornita in event.h stesso.
- Assegnare una struttura event_base all'heap globale come indicato nella documentazione. Assicurati di controllare il valore restituito per gli errori.
- Come sopra, ma allocare la struttura dell'evento . Nel mio caso, non sto aspettando alcun descrittore di file, quindi -1 viene passato come argomento. Inoltre, voglio che il mio evento persista, quindi EV_PERSIST. Il codice per le funzioni di callback è stato omesso.
- Schedule l'evento per l'esecuzione
- Avviare il ciclo degli eventi
- liberi le risorse quando fatto.
versione libevent utilizzato nel mio caso è libevent2 5.1.9, e si avrà anche bisogno di libevent_pthreads.so libreria per il collegamento.
evviva.
- 1. libevent, windows e programmazione .NET
- 2. Come utilizzare C++ e objective-c insieme in XCode 4.2
- 3. Come utilizzare i pthread con Android NDK?
- 4. Utilizzare loc e iloc insieme in panda
- 5. Discussioni in C, C++, C++ 0x, pthread e aumentare
- 6. Utilizzo di pthread in C++
- 7. Come posso utilizzare passportjs e reactjs insieme?
- 8. Come utilizzare insieme NSFetchedResultsController e UISearchController?
- 9. Come utilizzare IsKeyboardFocusWithin e IsSelected insieme?
- 10. Come utilizzare NSUbiquitousKeyValueStore e NSUserDefaults insieme
- 11. Utilizzare MongoEngine e PyMongo insieme
- 12. come utilizzare coord_carteisan e coord_flip insieme in ggplot2
- 13. Come fermarsi e continuare un pthread?
- 14. Come funziona il pthread?
- 15. Come utilizzare SSH e SUDO insieme TRAMP in Emacs
- 16. Come utilizzare il filtro nl2br e linky insieme in Angularjs?
- 17. Come utilizzare rowTemplate e detailTemplate insieme in KendoUI?
- 18. Come utilizzare MAX e LIMIT insieme in MySQL
- 19. Come utilizzare i moduli xlib e OpenGL insieme a python?
- 20. Moltiplicando char e int insieme in C
- 21. Impossibile utilizzare Scanner.nextInt() e Scanner.nextLine() insieme
- 22. Devo utilizzare sia SocialAuthenticationFilter e ProviderSignInController insieme
- 23. Pthread e condizioni di attesa
- 24. Come inviare e ricevere dati insieme all'evento in Objective-C?
- 25. concetti pthread in linux
- 26. come terminare un thread dormiente in pthread?
- 27. pthread in una classe
- 28. Come utilizzare insieme il routing di laravel e angularjs?
- 29. Utilizzare i parametri @Field e @Body in Retrofit insieme
- 30. Gulp: Come utilizzare Browsersync, Sourcemaps, Autoprefixer e CSS Cleaner insieme?
Questo è abbastanza facile da fare con i processi, se si guarda il relayd di OpenBSD, c'è il codice per più processi che gestiscono le richieste in entrata. – tbert