Invoking thread for each item in list simultaneously and returning value in Java

I made a wrapper for an API that I am using, basically what I’m doing is sending in a list of Series objects and for each item in the list, a thread (“worker”?) starts and fetches information for their respective series.

The API that I’m using doesn’t support fetching several series using one request, which would simplify this by a large margin, therefore I run threads for each item in the list.

I’m mostly concerned about the thread part, but I’ll provide all the other parts as well.

@RequestMapping(value = "/series", method = RequestMethod.POST) public List<Response> fetchSeveralSeries(@RequestBody List<Series> list) throws InterruptedException, ExecutionException {     List<Callable<Response>> callableList = new ArrayList<>();     for (int i = 0; i < list.size(); i++) {         callableList.add(new performRequest(list.get(i).getSeries()));     }      final ExecutorService service = Executors.newFixedThreadPool(list.size());     List<Future<Response>> futureObjects = service.invokeAll(callableList);     List<Response> series = new ArrayList<>();      for (Future<Response> obj : futureObjects) {         series.add(obj.get());     }      return series; } 

Callable class used. (temporarily in my Spring boot controller class, as my entire implementation is in the controller atm.)

private class performRequest implements Callable<Response> {     private int seriesId;      private performRequest(int seriesId) {         this.seriesId = seriesId;     }      @Override     public Response call() throws UnirestException {         return request.send(new Url(seriesId).toString());     } } 

About the request made by each thread, I have a Url class which constructs the Url for the request and a Request class which sends the request to the external API.

Request class which sends the request to external API. The Response object is a “GSON Object”.

@Service public class Request {      private static final Logger logger = LoggerFactory.getLogger(Request.class);      public Response send(String url) throws UnirestException {         logger.info("sending GET");         HttpResponse<JsonNode> json = Unirest.get(url).asJson();         String body = json.getBody().toString();         return new Gson().fromJson(body, Response.class);     }  } 

Url class which constructs the URL.

@Data public class Url {     private static final String BASE_URL = "https://api.themoviedb.org/3";     private static final String API_KEY = System.getenv("API_KEY");      private Integer id;     private Integer season;     private Integer episode;     private String searchQuery; // should turn spaces into %20      public Url(String searchQuery) {         this.searchQuery = searchQuery;     }      public Url(Integer id) {         this.id = id;     }      public Url(Integer id, Integer season) {         this.id = id;         this.season = season;     }      public Url(Integer id, Integer season, Integer episode) {         this.id = id;         this.season = season;         this.episode = episode;     }      @Override     public String toString() {         return this.searchQuery != null ?                 String.format("%s/search/tv?api_key=%s&language=en-US&query=%s", BASE_URL, API_KEY, this.searchQuery) : this.episode != null ?                 String.format("%s/tv/%s/season/%s/episode/%s?api_key=%s&language=en-US", BASE_URL, this.id, this.season, this.episode, API_KEY) : this.season != null ?                 String.format("%s/tv/%s/season/%s?api_key=%s&language=en-US", BASE_URL, this.id, this.season, API_KEY) :                 String.format("%s/tv/%s?api_key=%s&language=en-US", BASE_URL, this.id, API_KEY);     }  }  

An example POST request body would be something like below:

[     {         "series": 37680     },     {         "series": 53123     },     {         "series": 12345     },     {         "series": 29182     } ] 

Could my code be improved somehow? Would it be possible to decrease response time? Is it “thread-safe”?
Any feedback is welcome.

Invoking thread for each item in list simultaneously and returning value in Java

I made a wrapper for an API that I am using, basically what I’m doing is sending in a list of Series objects and for each item in the list, a thread (“worker”?) starts and fetches information for their respective series.

The API that I’m using doesn’t support fetching several series using one request, which would simplify this by a large margin, therefore I run threads for each item in the list.

I’m mostly concerned about the thread part, but I’ll provide all the other parts as well.

@RequestMapping(value = "/series", method = RequestMethod.POST) public List<Response> fetchSeveralSeries(@RequestBody List<Series> list) throws InterruptedException, ExecutionException {     List<Callable<Response>> callableList = new ArrayList<>();     for (int i = 0; i < list.size(); i++) {         callableList.add(new performRequest(list.get(i).getSeries()));     }      final ExecutorService service = Executors.newFixedThreadPool(list.size());     List<Future<Response>> futureObjects = service.invokeAll(callableList);     List<Response> series = new ArrayList<>();      for (Future<Response> obj : futureObjects) {         series.add(obj.get());     }      return series; } 

Callable class used. (temporarily in my Spring boot controller class, as my entire implementation is in the controller atm.)

private class performRequest implements Callable<Response> {     private int seriesId;      private performRequest(int seriesId) {         this.seriesId = seriesId;     }      @Override     public Response call() throws UnirestException {         return request.send(new Url(seriesId).toString());     } } 

About the request made by each thread, I have a Url class which constructs the Url for the request and a Request class which sends the request to the external API.

Request class which sends the request to external API. The Response object is a “GSON Object”.

@Service public class Request {      private static final Logger logger = LoggerFactory.getLogger(Request.class);      public Response send(String url) throws UnirestException {         logger.info("sending GET");         HttpResponse<JsonNode> json = Unirest.get(url).asJson();         String body = json.getBody().toString();         return new Gson().fromJson(body, Response.class);     }  } 

Url class which constructs the URL.

@Data public class Url {     private static final String BASE_URL = "https://api.themoviedb.org/3";     private static final String API_KEY = System.getenv("API_KEY");      private Integer id;     private Integer season;     private Integer episode;     private String searchQuery; // should turn spaces into %20      public Url(String searchQuery) {         this.searchQuery = searchQuery;     }      public Url(Integer id) {         this.id = id;     }      public Url(Integer id, Integer season) {         this.id = id;         this.season = season;     }      public Url(Integer id, Integer season, Integer episode) {         this.id = id;         this.season = season;         this.episode = episode;     }      @Override     public String toString() {         return this.searchQuery != null ?                 String.format("%s/search/tv?api_key=%s&language=en-US&query=%s", BASE_URL, API_KEY, this.searchQuery) : this.episode != null ?                 String.format("%s/tv/%s/season/%s/episode/%s?api_key=%s&language=en-US", BASE_URL, this.id, this.season, this.episode, API_KEY) : this.season != null ?                 String.format("%s/tv/%s/season/%s?api_key=%s&language=en-US", BASE_URL, this.id, this.season, API_KEY) :                 String.format("%s/tv/%s?api_key=%s&language=en-US", BASE_URL, this.id, API_KEY);     }  }  

An example POST request body would be something like below:

[     {         "series": 37680     },     {         "series": 53123     },     {         "series": 12345     },     {         "series": 29182     } ] 

Could my code be improved somehow? Would it be possible to decrease response time? Is it “thread-safe”?
Any feedback is welcome.

Exception in thread “AWT-EventQueue-0” java.lang.NullPointerException en socket

Quisiera solicitar su ayuda para resolver un error en java. He estado mirando en el foro algunos problemas similares pero no he encontrado soluciones satisfactorias a mi problema.

El programa es un ejemplo básico de sockets con cliente y servidor.

Sin embargo cada vez que se ejecuta el cliente, al intentar enviar datos genera el siguiente error:

run: Conectado OK  Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException     at proxy.SocketConnect.writeLine(SocketConnect.java:51)     at main.EnviodeDatos.actionPerformed(EnviodeDatos.java:50)     at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)     at javax.swing.AbstractButton$  Handler.actionPerformed(AbstractButton.java:2348)     at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)     at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)     at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)     at java.awt.Component.processMouseEvent(Component.java:6539)     at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)     at java.awt.Component.processEvent(Component.java:6304)     at java.awt.Container.processEvent(Container.java:2239)     at java.awt.Component.dispatchEventImpl(Component.java:4889)     at java.awt.Container.dispatchEventImpl(Container.java:2297)     at java.awt.Component.dispatchEvent(Component.java:4711)     at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4904)     at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4535)     at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4476)     at java.awt.Container.dispatchEventImpl(Container.java:2283)     at java.awt.Window.dispatchEventImpl(Window.java:2746)     at java.awt.Component.dispatchEvent(Component.java:4711)     at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:760)     at java.awt.EventQueue.access$  500(EventQueue.java:97)     at java.awt.EventQueue$  3.run(EventQueue.java:709)     at java.awt.EventQueue$  3.run(EventQueue.java:703)     at java.security.AccessController.doPrivileged(Native Method)     at java.security.ProtectionDomain$  JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:74)     at java.security.ProtectionDomain$  JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:84)     at java.awt.EventQueue$  4.run(EventQueue.java:733)     at java.awt.EventQueue$  4.run(EventQueue.java:731)     at java.security.AccessController.doPrivileged(Native Method)     at java.security.ProtectionDomain$  JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:74)     at java.awt.EventQueue.dispatchEvent(EventQueue.java:730)     at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:205)     at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)     at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)     at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)     at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)     at java.awt.EventDispatchThread.run(EventDispatchThread.java:82) 

El programa es el siguiente:

EnviodeDatos (main):

package main;  import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Scanner;  import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JTextField;  import proxy.SocketConnect; import proxy.SocketInter; import proxy.SocketInter; import proxy.SocketConnect;  public class EnviodeDatos extends JFrame implements ActionListener {      JTextField textmensaje;     JButton btsend;      /**      *      */     public EnviodeDatos() {         textmensaje = new JTextField();         textmensaje.setBounds(10, 10, 200, 120);         add(textmensaje);         btsend = new JButton();         btsend.setText("SEND");         btsend.setBounds(10, 135, 120, 20);         btsend.addActionListener((ActionListener) this);         add(btsend);         setLayout(null);         setSize(400, 400);         setVisible(true);     }      public static void main(String[] args) {         // TODO Auto-generated method stub         new EnviodeDatos();     }      @Override     public void actionPerformed(ActionEvent arg0) {         // TODO Auto-generated method stub         if (arg0.getSource() == btsend) {              SocketInter socket = (SocketInter) new SocketConnect("127.0.0.1", 8080);             socket.writeLine(textmensaje.getText());              socket.dispose();          }     }  } 

interface socket

package proxy;  public interface SocketInter {     String readLine();     void  writeLine(String str);     void  dispose(); } 

socket concreto

package proxy;  import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket;  public class SocketConnect implements SocketInter {      private Socket socket;     private BufferedReader in;     private PrintWriter out;      /**      * @param socket      * @param in      * @param out      */     public SocketConnect(String host, int port) {         try {              Socket socket = new Socket(host, port);             in = new BufferedReader(new InputStreamReader(socket.getInputStream()));             out = new PrintWriter(socket.getOutputStream(), true);             System.out.println("Conectado OK ");         } catch (IOException e) {             System.out.println(e.getMessage());          }     }      @Override     public String readLine() {         String str = null;         try {             str = in.readLine();         } catch (IOException e) {             e.printStackTrace();         }         return str;     }      @Override     public void writeLine(String str) {         // TODO Auto-generated method stub         // 4. The wrapper delegates to the target         try {             DataOutputStream data = new DataOutputStream(socket.getOutputStream());              data.writeUTF(str);             System.out.println("Dato enviado");          } catch (IOException e) {             // TODO Auto-generated catch block             System.out.println("Dato no enviado: " + e.getMessage());         }      }      @Override     public void dispose() {         // TODO Auto-generated method stub         try {             socket.close();          } catch (IOException e) {             e.printStackTrace();         }     } } 

He revisado pero no encuentro problema, igual debo decir que mis conocimientos en java son muy básicos. Les agradecería cualquier ayuda que puedan brindarme.

Discussion replies via E-mail creates new thread

I have a Community site which contains a Discussion List, I have configured In-coming emails for this list and subscribed the alerts for the same list. When i send a email to the configured list email id for first time it creates a new Discussion post as expected, but after that if i try sending email to same post for reply via mail received from alert it creates a new Post insted of reply to discussion. Has anyone faced similiar situation ? please help me to fix this.

Read 1 line for. each thread

a short time ago a simple script to find the panel of a website, I wanted to try again to do it with thread but after a while I got stuck.

My code takes 2 path files to create one with all the combinations and puts it in a “results” variable. I didn’t understand how I can (if I can) make each thread take a line of the file and execute the function that should …

//variable with site + word combination results = [site+word for site in sites for word in words]

for line in results: line2 = str(line)

def run(n, name): print(‘ {}. ‘.format(line2))

// request… status code ecc…

time.sleep(n) print('{} finish'.format(line2)) 

start = time.time() for i in range(5): t = threading.Thread(target=run, name=’thread{}’.format(i) , args=(3, ‘thread{}’.format(line2)))

thread_list.append(t) t.start() print('{} è partito'.format(t.name)) 

for t in thread_list: t.join()

end = time.time() print(“time taken : {}”.format(end-start))

Output : Hi http://uno.com/santissimo. thread0 go Hi http://uno.com/santissimo. thread1 go Hi http://uno.com/santissimo. thread2 go Hi http://uno.com/santissimo. thread3 go Hi http://uno.com/santissimo. thread4 go [OK] 200 [OK] 200 [OK] 200 [OK] 200 [OK]

I want my threads take 1 line of the result var, and start doing the run function … Where I’m wrong ? Thanks all

Detecting deadlocks in thread safe linked list

I recently got a homework to implement a thread safe singly linked list which locks elements in hand over hand method which means that there is a single lock for every element in the list.I implemented all the functions and tested them without having to deal with problematic thread situations and they all worked but I wanted to test if there could be a situation of a deadlock or a starvation but I do not know how to do it and can I know from looking at my code if I could have deadlock or starvation ? I am also not sure if there there needs to be this much locking and unlocking in the code. Any help or suggestion regarding my code if it its prone to deadlocks and starvation or any other problems ? I will post my code below. Thanks in advance.

concurrent_list.h :

typedef struct node node; typedef struct list list;  list* create_list(); void delete_list(list* list); void print_list(list* list); void insert_value(list* list, int value); void remove_value(list* list, int value); void count_list(list* list, int (*predicate)(int)); 

concurrent_list.c :

 #include <pthread.h>  #include <stdio.h>  #include <stdlib.h>  #include <limits.h>  #include "concurrent_list.h"  struct node {   int value;   node* next;   pthread_mutex_t lock; // hand over hand implies a lock for every node };  struct list {   node* head; };  // print the value of a node void print_node(node* node) {   if(node)   {     printf("%d ", node->value);   }  }  // create  a new empty list list* create_list() {     list* l =(list*)malloc(sizeof(list));      if(l == NULL) return NULL;      l->head = NULL;      return l; }  // delete the entire list void delete_list(list* list) {   if(list == NULL) return; // if list pointer is NULL then do nothing    node* current = list->head;    if(current == NULL) return; // if list head is NULL then do nothing    pthread_mutex_lock(&(current->lock)); // lock list head    node* temp = current->next;   node* dummy;    if(temp == NULL) // delete the only element in the list   {      pthread_mutex_unlock(&(current->lock));      pthread_mutex_destroy(&(current->lock));      free(current);      return;   }    pthread_mutex_lock(&(temp->lock)); //lock successor of the head    while (1)   {      pthread_mutex_unlock(&(current->lock)); // unlock current node      dummy = current;      current = temp; // current becomes it's successor      pthread_mutex_destroy(&(dummy->lock));      free(dummy); // free dummy because it is a pointer to current      temp = temp->next; // current becomes it's successor      if(temp == NULL) break; // exit loop if we are at the end of the       list      pthread_mutex_lock(&(temp->lock)); // lock current's successor   }       pthread_mutex_unlock(&(current->lock));      pthread_mutex_destroy(&(current->lock));      free(current); // free the last element in the list      list->head = NULL;      free(list); // free the list   }    // insert function for a new value if a value already exists then do    nothing   void insert_value(list* list, int value)   {      if(list == NULL) return; // if list pointer is NULL then do nothing       node* new_node = malloc(sizeof(node)); // create new node       if(new_node == NULL) return; // check if allocation fails       new_node->value = value;       new_node->next = NULL;       pthread_mutex_init(&(new_node->lock),NULL);  // initialize fast mutex lock for the new node       pthread_mutex_lock(&(new_node->lock)); // lock the new node       if(list->head == NULL) // new node is the first element in the list      {         new_node->next = NULL;         list->head = new_node;         pthread_mutex_unlock(&(new_node->lock));         return;      }        pthread_mutex_lock(&(list->head->lock)); // lock the head of the list        node* temp;        if(list->head->value >= new_node->value) // new node comes before the list head      {        new_node->next = list->head;        temp = list->head;        list->head = new_node;        pthread_mutex_unlock(&(list->head->lock));        pthread_mutex_unlock(&(temp->lock));        return;      }      else     {       // Locate the node before the point of insertion //       node* dummy;      node* current = list->head;      temp = current->next;       if(temp == NULL) // new node comes after the list head      {          new_node->next = current->next;          current->next = new_node;          pthread_mutex_unlock(&(new_node->lock));          pthread_mutex_unlock(&(current->lock));          return;      }      pthread_mutex_lock(&(temp->lock)); // lock the successor of the head    // perform hand over hand traversal of the list   // and check if temp reaches the end of the list (NULL)     while (temp->value < new_node->value)    {      pthread_mutex_unlock(&(current->lock));      current = temp;      temp = temp->next;      if(temp == NULL) break;      pthread_mutex_lock(&(temp->lock));    }     if(temp == NULL) // new node will be the last element in this case    {        current->next = new_node;        new_node->next = NULL;        pthread_mutex_unlock(&(current->lock));        pthread_mutex_unlock(&(new_node->lock));        return;    }     else // new node should be inserted inside the list    {        dummy = temp;        new_node->next = current->next;        current->next = new_node;        pthread_mutex_unlock(&(dummy->lock));        pthread_mutex_unlock(&(current->lock));        pthread_mutex_unlock(&(new_node->lock));        return;    }  } }   //delete the first appearance of a value in the list if it exists in the list     void remove_value(list* list, int value)     {       if(list == NULL) return; // if list pointer is NULL then do nothing        node* temp;       node* current = list->head;        if(current == NULL) return; // if list head is NULL then just go to a new line       pthread_mutex_lock(&(current->lock)); // lock the head of the list       if(current->value == value) // delete the head of list if it's value is equal to given value     {         temp = current;         list->head = current->next;         pthread_mutex_unlock(&(temp->lock));         pthread_mutex_destroy(&(temp->lock));        free(temp);        return;    }      else    {        temp = current->next;         if(temp == NULL)        {            pthread_mutex_unlock(&(current->lock));            return;        }         pthread_mutex_lock(&(temp->lock)); // lock the successor of the head          // perform hand over hand traversal of the list        //  and check if temp reaches the end of the list (NULL)      while (temp->value != value) // find the first appearance of a node      that has a value the same as the one given         {           pthread_mutex_unlock(&(current->lock));           current = temp;           temp = temp->next;           if(temp == NULL) break;           pthread_mutex_lock(&(temp->lock));         }           if(temp == NULL) // value not found         {             pthread_mutex_unlock(&(current->lock));             return;         }          else // delete the suitable node         {             current->next = temp->next;             pthread_mutex_unlock(&(current->lock));             pthread_mutex_unlock(&(temp->lock));             pthread_mutex_destroy(&(temp->lock));             free(temp);            return;         }     } }   //print the entire list  void print_list(list* list)  {   if(list == NULL) // if list pointer is NULL then just go to a new line   {       printf("\n");       return;   }        node* current = list->head;        if(current == NULL) // if list head is NULL then just go to a new line       {          printf("\n");          return;       }        pthread_mutex_lock(&(current->lock)); // lock the head of the list        print_node(current); // print the head of the list        node* temp = current->next;        if(temp == NULL) // a list with 1 element       {          printf("\n");          pthread_mutex_unlock(&(current->lock));          return;       }       pthread_mutex_lock(&(temp->lock)); // lock the list head's successor      while (1)     {        pthread_mutex_unlock(&(current->lock)); // unlock current node        current = temp; // current becomes it's successor        print_node(current); // print current node        temp = temp->next; // // temp becomes it's successor        if(temp == NULL) break; // exit loop if we reach the end of the list       pthread_mutex_lock(&(temp->lock)); // lock temp    }      pthread_mutex_unlock(&(current->lock)); // unlock the last list      element    printf("\n"); }   // print how many nodes in the list satisfy a given predicate function  void count_list(list* list, int (*predicate)(int))  {     int count = 0;     if(list == NULL) // if list pointer is NULL then print that count =     0 and finish    {       printf("%d items were counted\n", count);       return;    }     node* current = list->head;     if(current == NULL) // if list head is NULL then print that count =     0 and finish    {        printf("%d items were counted\n", count);        return;    }     pthread_mutex_lock(&(current->lock)); // lock the list head     if(predicate(current->value)) count++; // check the predicate for     the list head     node* temp = current->next;     if(temp == NULL) // list has only 1 element    {       pthread_mutex_unlock(&(current->lock));       printf("%d items were counted\n", count);       return;    }     pthread_mutex_lock(&(temp->lock)); // lock the list head's successor     while (1)   {     pthread_mutex_unlock(&(current->lock)); // unlock current node     current = temp; // current becomes it's successor     if(predicate(current->value)) count++; // check predicate for current node     temp = temp->next; // // temp becomes it's successor     if(temp == NULL) break; // exit loop if we reach the end of the list     pthread_mutex_lock(&(temp->lock)); // lock temp    }     pthread_mutex_unlock(&(current->lock)); // unlock the last list element     printf("%d items were counted\n", count); // print count } 

Indian Passport thread coming off

We gave our passport for stamping and it looks like it returned with threads coming out lose. My passport has only 2 threads remaining.

We are travelling to a couple of countries before going to India (And then get visa stamped).

Did anyone visit the consulate and can they fix it? It should work with a glue but I dont want to mess with passorts.

Como filtrar categoría de tipo thread en wordpress?

estoy intentando filtrar las por categorias las entradas de tipo thread, ya que estoy utilizando la plantilla ForumEngine, en la home quiero mostrar por ejemplo: Vegetales, carnes, condimentos, esas serian las categorias quiero mostrar 5 post del tipo thread de cada categoria en la misma home ,

tengo la plantilla sin editar, con el siguiente codigo muestra todas las entradas de tipo thread sin filtro alguno.

<?php  get_header(); global $  wp_query, $  wp_rewrite, $  post, $  current_user , $  user_ID, $  wpdb;  $  data = et_get_unread_follow(); $  term = get_term_by( 'slug' , get_query_var( "term" ), 'thread_category') ; ?> <div class="header-bottom header-filter">     <div class="main-center container">         <?php             fe_navigations();         ?>     </div>     <div class="mo-menu-toggle visible-sm visible-xs">         <a class="icon-menu-tablet" href="#"><?php _e('open', ET_DOMAIN ) ?></a>     </div> </div> <!--end header Bottom-->    <div class="container main-center">     <div class="row">         <div class="col-md-9 col-sm-12 marginTop30">             <?php get_template_part('template/post', 'thread'); ?>             <?php             $  page           = get_query_var('page') ? get_query_var('page') : 1;             $  sticky_threads = et_get_sticky_threads();             $  thread_query = FE_Threads::get_threads(array(                 'post_type'     => 'thread',                 'paged'         => $  page,                 //'tag_ID' => 2,                 'post__not_in'  => $  sticky_threads[0]             ));              if (  $  thread_query->have_posts() ){ ?>                 <ul id="main_list_post" class="list-post">                     <?php                     if ( !empty( $  sticky_threads[0] ) ){                         // load sticky thread                         get_template_part( 'template/sticky', 'thread' );                     }           </div>      </div> </div> 

e omitido código ya que no me deja poner todo el código de la plantilla

Right thread implementation in frequently invoked method

I am fresh in c++

But actually what I am interested in :

I have such method

void VideoRender::updateData(const std::string &i_obj_path, const std::string &i_pngPath, const uint i_subIndex) {     std::shared_ptr<FrameManager> container = std::make_shared<FrameManager>();      std::thread th1(&VideoRender::thread_task1, this, i_obj_path.c_str(), i_subIndex, container);     std::thread th2(&VideoRender::thread_task2, this, i_pngPath, container);      th1.join();     th2.join();      fifo.enqueue(container); } 

As you can see, this method is executing 2 task in 2 different threads and then join them. I invoke this method 20 times per second.

What bothers me: that 20 times per second I create 2 threads…

Question is: if this implementation in c++ looks ok? Because I think I should to use something like ThreadPool or some Handler that will run in another thread and I will push the task‘s there…

If am I right?

Right thread implementation in frequently invoked method

I am fresh in c++

But actually what I am interested in :

I have such method

void VideoRender::updateData(const std::string &i_obj_path, const std::string &i_pngPath, const uint i_subIndex) {     std::shared_ptr<FrameManager> container = std::make_shared<FrameManager>();      std::thread th1(&VideoRender::thread_task1, this, i_obj_path.c_str(), i_subIndex, container);     std::thread th2(&VideoRender::thread_task2, this, i_pngPath, container);      th1.join();     th2.join();      fifo.enqueue(container); } 

As you can see, this method is executing 2 task in 2 different threads and then join them. I invoke this method 20 times per second.

What bothers me: that 20 times per second I create 2 threads…

Question is: if this implementation in c++ looks ok? Because I think I should to use something like ThreadPool or some Handler that will run in another thread and I will push the task‘s there…

If am I right?