#include "my_sys.h" #include "pthread.h" #include "time.h" #include "ring_buffer.hpp" #include RingBuffer *cache; uchar *buff_from; uchar *buff_to; pthread_barrier_t barrier; void *read_to_cache(void *) { pthread_barrier_wait(&barrier); for (int i= 0; i < 32; ++i) { cache->read_slot(buff_to + (i * 255), 255); } return NULL; } void *write_to_cache(void *args) { struct st_my_thread_var thdvar; set_mysys_var(&thdvar); pthread_barrier_wait(&barrier); int *v_args= (int *) args; for (int i= v_args[0]; i < v_args[1]; ++i) cache->write_slot(buff_from + (i * 255), 255); return NULL; } void *write_to_cache_one(void*) { for (int i= 0; i < 32; ++i) cache->write_slot(buff_from + (i * 255), 255); return NULL; } int main() { static const int thread_write_count= 4; static const int part_of_data_for_writers = 8; static const int size_buffer = 10000; clock_t tss, tee; int args[8]; pthread_t thr_read; pthread_t *thr_write= (pthread_t *) malloc(8 * sizeof(pthread_t)); buff_to= (uchar *) malloc(sizeof(uchar) * size_buffer); buff_from = (uchar*) malloc(sizeof(uchar) * size_buffer); pthread_barrier_init(&barrier, NULL, thread_write_count + 1); { std::ofstream off; off.open("random.txt"); char c; int r; srand (0); for (int i=0; i<8160; i++) { r = i % 4; // generate a random number if(r == 3) { buff_from[i] = '\n'; continue; } c = 'a' + rand() % 26; // Convert to a character from a-z buff_from[i] = c; } off << buff_from; // copy generated bytes to file } remove("cache_file.txt"); // re-create cache file on each start tss= clock(); cache= new RingBuffer((char *) "cache_file.txt", 4096); for (int i= 0; i < thread_write_count; ++i) { args[i * 2]= i * part_of_data_for_writers; args[(i * 2) + 1]= (i + 1) * part_of_data_for_writers; pthread_create(&thr_write[i], NULL, write_to_cache, (void *) &args[i * 2]); } pthread_create(&thr_read, NULL, read_to_cache, NULL); for (int i= 0; i < thread_write_count; ++i) pthread_join(thr_write[i], NULL); pthread_join(thr_read, NULL); delete cache; tee= clock(); printf("Time: %lld\n", (long long) tee - tss); std::ofstream of; of.open("test_out.txt", std::ios_base::out); of << buff_to; return 0; }