The document is very vague about how to register a function. It turned out that the prototype/signature of the function
gearman_worker_fn is very import:
typedef void*( gearman_worker_fn)(gearman_job_st *job, void *context, size_t *result_size, gearman_return_t *ret_ptr)
And since all the online document links are broken, I had to create using Doxygen, under folder /usr/local/include/libgearman-1.0
#include <iostream>
#include <libgearman/gearman.h>
#include <cstring>
using namespace std;
void* gworker_fn_demon(gearman_job_st *job, void *context, size_t *result_size, gearman_return_t *ret_ptr)
{
auto jobptr = gearman_job_workload(job);//this takes the data from the client
if (jobptr) std::cout << "job: " << (char*) jobptr << std::endl;
*ret_ptr = GEARMAN_SUCCESS ;
*result_size = 6;
cout<<"job received"<<endl;
//char* result = new char[100];//bug here: free/new mismatch reported from valgrind
char* result = (char*)malloc(100 * sizeof(char));
for(int ii = 0; ii < 4; ++ii){
result[ii] = 'a' + ii;
}
result[4] = '\n';
result[5] = '\0';
return result;//the memory is freed at client side
}
int main()
{
auto status_print = [](gearman_return_t gserver_code){
cout<<gserver_code<< " -- ";
if (gearman_success(gserver_code)) cout<<"success";
if (gearman_failed(gserver_code)) cout<<"failed";
if (gearman_continue(gserver_code)) cout<<"continue";
cout<<endl;
};
gearman_worker_st* gworker = gearman_worker_create(NULL);
const char* ghost = "127.0.0.1";
in_port_t gport = 4730;
gearman_return_t gs_code = gearman_worker_add_server(gworker, ghost, gport);
status_print(gs_code);
const char* function_name = "wwcc";
unsigned timeout = 0;
void * job_context = NULL;
gs_code = gearman_worker_add_function(gworker,function_name, timeout, gworker_fn_demon, job_context);
status_print(gs_code);
gs_code = gearman_worker_work(gworker);
status_print(gs_code);
gearman_worker_free(gworker);
cout<<"done"<<endl;
return 0;
}
No comments:
Post a Comment