VC++ threads deadlocked - multithreading

The following program goes into a deadlock. Can anyone please tell me why?
#include<cstdlib>
#include<windows.h>
#include<iostream>
using namespace std;
class CircularQueue
{
public:
CircularQueue(int s)
{
size = s;
array = (int*)malloc(sizeof(int) * size);
head = tail = -1;
InitializeCriticalSection(&critical_section);
}
CircularQueue(void)
{
size = default_size;
array = (int*)malloc(sizeof(int) * size);
head = tail = -1;
InitializeCriticalSection(&critical_section);
}
void initialize(int s)
{
EnterCriticalSection(&critical_section);
size = s;
array = (int*)realloc(array, sizeof(int) * size);
head = tail = -1;
LeaveCriticalSection(&critical_section);
}
void enqueue(int n)
{
EnterCriticalSection(&critical_section);
tail = (tail + 1) % size;
array[tail] = n;
LeaveCriticalSection(&critical_section);
}
int dequeue(void)
{
EnterCriticalSection(&critical_section);
head = (head + 1) % size;
return array[head];
LeaveCriticalSection(&critical_section);
}
private:
int *array;
int size;
int head, tail;
CRITICAL_SECTION critical_section;
bool initialized;
static const int default_size = 10;
};
DWORD WINAPI thread1(LPVOID param)
{
CircularQueue* cqueue = (CircularQueue*)param;
cqueue->enqueue(2);
cout << cqueue->dequeue() << endl;
return 0;
}
DWORD WINAPI thread2(LPVOID param)
{
CircularQueue* cqueue = (CircularQueue*)param;
cqueue->enqueue(3);
cout << cqueue->dequeue() << endl;
return 0;
}
int main(void)
{
HANDLE thread1_handle;
HANDLE thread2_handle;
CircularQueue cqueue;
HANDLE array[2];
thread1_handle = CreateThread(NULL, 0, thread1, &cqueue, 0, NULL);
thread2_handle = CreateThread(NULL, 0, thread2, &cqueue, 0, NULL);
array[0] = thread1_handle;
array[1] = thread2_handle;
WaitForMultipleObjects(1, array, TRUE, INFINITE);
CloseHandle(thread1_handle);
CloseHandle(thread2_handle);
printf("end\n");
return 0;
}

In dequeue(), you have a return statement before the LeaveCriticalSection() call. If you had compiler warnings turned up higher, it would probably have told you about this!

Related

define dynamic array inside a struct without causing a segmentation fault

I'm new to c++ and I have to work with dynamic arrays:| I need to define a few dynamic arrays inside my header file and access them from main. The problem is that when I'm defining the arrays inside the structs, I get segmentation faults and don't know how to fix them.
Below is my header file.
I'm aware that there are lots of problems with my code and I could use your help. I'm really stuck here.
Thanks in advance.
I expect this code to work fine with dynamic arrays just like it does with vectors. But it's not.
`
#pragma once
#include <iostream>
#include <functional>
#include <algorithm>
#define children_link_Size 149
#define row 15
#define col 100
using namespace std;
int itemListIndex = 0;
int freqIdx = 0;
int childIdx = 0;
int linkIdx = 0;
namespace std {
template <typename T> T* begin(std::pair<T*, T*> const& p)
{
return p.first;
}
template <typename T> T* end(std::pair<T*, T*> const& p)
{
return p.second;
}
}
struct Node
{
int itemValue{};
int order{ 0 };
int freq{ 0 };
Node* parent{ nullptr };
Node* children{};
Node* links{};
Node() {
children = new Node[children_link_Size];
links = new Node[children_link_Size];
}
explicit Node(int const& p_value, int p_order = 0) :itemValue(p_value), order(p_order)
{
++freq;
cout << " + " << itemValue << " (" << order << ")" << endl;
}
bool operator ==(Node const& p_node) const
{
return itemValue == p_node.itemValue;
}
~Node() {
delete[] children;
delete[] links;
}
};
/*struct mySet {
Node* OrderedItems;
mySet()
{
OrderedItems = new Node[uniqueSize];
}
void insert(Node item)
{
for (int i = 0; i < uniqueSize; i++)
{
for (int j = 0; j < i; j++)
{
if (item == OrderedItems[j])
{
break;
}
else
{
OrderedItems[i] = item;
}
}
}
}
~mySet()
{
delete[] OrderedItems;
}
};*/
struct ItemSupport
{
explicit ItemSupport(int p_minSup) { ItemSupport::minSup = p_minSup; }
Node* Itemset = new (nothrow) Node[row];
Node* OrderedItems = new (nothrow) Node[row];
ItemSupport& operator<<(int const& p_itemValue)
{
static int order = 0;
auto inode = find_if(Itemset, Itemset + row, [&p_itemValue](Node const& p_node)
{
return p_node.itemValue == p_itemValue;
});
if (inode == Itemset + row)
{
Node node(p_itemValue, order);
Itemset[itemListIndex] = node;
itemListIndex++;
++order;
}
else
{
auto& node = (*inode);
++node.freq;
}
return *this;
}
friend ostream& operator<<(ostream& p_os, ItemSupport const& p_itemSupport)
{
ItemSupport* NoDe = {0};
if (NoDe)
{
NoDe->OrderedItems = p_itemSupport.getFrequentItems();
for (Node node : std::make_pair(NoDe->OrderedItems, NoDe->OrderedItems + row))
{
p_os << node.itemValue << ": support " << node.freq << ", order " << node.order << endl;
}
return p_os;
}
}
Node* getItem(int const& p_itemValue)
{
auto inode = find_if(Itemset, Itemset + row, [&p_itemValue](Node const& p_node)
{
return p_node.itemValue == p_itemValue;
});
if (inode != Itemset + row)
{
Node* node = const_cast<Node*>(&(*inode));
return node;
}
return nullptr;
}
static int getMinSup()
{
return minSup;
}
static int minSup;
private:
Node* getFrequentItems() const
{
int j = 0;
for (int i = 0; i < row; i++)
{
if (Itemset[i].freq >= minSup)
OrderedItems[j++] = Itemset[i];
}
return OrderedItems;
}
Node* getUnfrequentItems() const
{
int j = 0;
for (int i = 0; i < row; i++)
{
if (Itemset[i].freq <= minSup)
OrderedItems[j++] = Itemset[i];
}
return OrderedItems;
}
/*~ItemSupport() {
//delete[] Itemset;
//delete[] OrderedItems;
}*/
};
int ItemSupport::minSup = 0;
struct FP_Tree
{
explicit FP_Tree(ItemSupport& p_itemSupport, const int& p_rootValue = int()) :_headItemSupport(p_itemSupport)
{
_root = new Node(p_rootValue);
}
//void construct(Transaction const& p_itemValues)
void construct(int *p_itemValues)
{
// A. Order items into transaction
ItemSupport* ordered = {0};
for (int const& itemValue : std::make_pair(p_itemValues, p_itemValues + row))
{
Node* pNode = _headItemSupport.getItem(itemValue);
if (pNode && pNode->freq >= ItemSupport::getMinSup())
{
if (ordered)
{
ordered->OrderedItems[freqIdx] = *pNode;
freqIdx++;
}
}
}
// B. Create FP_TREE
Node* actualNode = _root;
bool here = true;
string tab;
if (ordered)
{
for (Node const& node : std::make_pair(ordered->OrderedItems, ordered->OrderedItems + row))
{
tab += "\t-";
auto it = actualNode->children;
if (here)
{
auto it = find_if(actualNode->children,
actualNode->children + children_link_Size,
[&node](Node const& nodeTmp) {
return node == (nodeTmp);
});
here &= it != actualNode->children + children_link_Size;
}
if (here)
{
actualNode = it;
++actualNode->freq;
}
else
{
Node* pNode = new Node(node.itemValue);
actualNode->children[childIdx++] = *pNode;
pNode->parent = actualNode;
Node* pNodeHead = _headItemSupport.getItem(node.itemValue);
pNodeHead->links[linkIdx++] = *pNode;
actualNode = pNode;
delete pNode;
}
//cout << tab << actualNode->_itemValue << "(" << actualNode->_freq << ")" << endl;
}
}
//cout << endl;
}
ItemSupport& headItemSupport() const
{
return _headItemSupport;
}
public:
Node* root() const
{
return _root;
}
private:
ItemSupport& _headItemSupport;
Node* _root;
};
`
I expect this code to work fine with dynamic arrays just like it does with vectors
Since you are using C++, do use std::vector -- it will save you a lot of trouble and there is no reason not to.

getting response only on the first time with socket programming

I'm trying to create an HTTP server using C++ 98.
The issue is that, every time I launch my server, I get the response, sending again the request from the same browser tab, and the browser keeps loading.
In my kqueue, it seems like the block for checking the read event is not being executed on the second time.
This is my code:
void webserv::Server::lunch(){
this->kq.create_event(this->sock.getSocket(), EVFILT_READ);
while(1)
this->_lunch_worker();
}
void webserv::Server::_lunch_worker(void)
{
int n_ev;
int accept_sock;
int address_size;
char buff[1000];
webserv::Header header;
// register the events in ev_list
std::cout << GREEN << "---- WAITING FOR CONNECTION ----" << RESET << std::endl;
n_ev = this->kq.get_event();
for (int i = 0; i < n_ev; i++)
{
if (this->kq.get_fd(i) < 0)
continue;
if (this->kq.get_fd(i) == this->sock.getSocket())
{
std::cout << "--- RECEIVED NEW CONNECTION ---" << std::endl;
address_size = sizeof(this->sock.getAddress());
accept_sock = accept(
this->sock.getSocket(),
(struct sockaddr*)&this->sock.getAddress(),
(socklen_t *)&address_size
);
this->sock.test_error(accept_sock);
this->kq.create_event(accept_sock, EVFILT_READ);
int flags;
if ((flags = fcntl(accept_sock, F_GETFL, 0)) < 0) {
perror("fcntl");
close(accept_sock);
close(this->sock.getSocket());
}
if (fcntl(accept_sock, F_SETFL, flags | O_NONBLOCK) < 0) {
perror("fcntl");
close(accept_sock);
close(this->sock.getSocket());
}
this->kq.create_event(accept_sock, EVFILT_WRITE, EV_ADD | EV_ONESHOT);
}
else if (this->kq.is_read_available(i))
{
int bytes_read;
std::cout << "START: is_read_available" << std::endl;
if ((bytes_read = recv(this->kq.get_fd(i), buff, 999, 0)) > 0)
{
}
}
else if (this->kq.is_write_available(i))
{
std::string hello = "HTTP/1.1 200 OK\nContent-Type: text/plain\nContent-Length: 12\n\nHello world!";
if (send(this->kq.get_fd(i), hello.c_str(), hello.length(), 0) != 0)
{
std::cout << "TEST2" << std::endl;
this->kq.set_event(this->kq.get_fd(i), EVFILT_WRITE, EV_DELETE);
this->kq.get_event_list()[i].ident = -1;
close(this->kq.get_fd(i));
}
std::cout << "END: is_write_available" << std::endl;
}
}
}
And this is the kqueue class:
/************************ CONSTRUCTORS/DESTRUCTOR ************************/
webserv::Kqueue::Kqueue()
{
this->_kq = kqueue();
std::cout << "KQUEUE CREATED" << std::endl;
this->test_error(this->_kq, "Creating Kqueue :");
this->_n_ev = 0;
}
webserv::Kqueue::~Kqueue()
{
close(this->_kq);
}
/************************ MEMBER FUNCTIONS ************************/
void webserv::Kqueue::set_event(int fd, int filter, int flags, void *udata)
{
EV_SET(&this->_ev_set, fd, filter, flags, 0, 0, udata);
}
void webserv::Kqueue::add_event(void)
{
int ret;
ret = kevent(this->_kq, &this->_ev_set, 1, NULL, 0, NULL);
this->test_error(ret, "Kqueue/add_even functions");
}
int webserv::Kqueue::get_event(void)
{
this->_n_ev = kevent(this->_kq, NULL, 0, this->_ev_list, __EV_LIST_SIZE__, NULL);
this->test_error(this->_n_ev, "Kqueue/get_event function:");
return (this->_n_ev);
}
void webserv::Kqueue::create_event(int fd, int filter, int flags, void *udata)
{
this->set_event(fd, filter, flags, udata);
this->add_event();
}
bool webserv::Kqueue::isEOF(int index)
{
if (this->_n_ev <= index)
this->test_error(-1, "Kqueue/isEOF function:");
return (this->_ev_list[index].flags & EV_EOF);
}
bool webserv::Kqueue::is_read_available(int index)
{
if (this->_n_ev <= index)
this->test_error(-1, "Kqueue/is_read_available function:");
return (this->_ev_list[index].filter == EVFILT_READ);
}
bool webserv::Kqueue::is_write_available(int index)
{
if (this->_n_ev <= index)
this->test_error(-1, "Kqueue/is_write_available function:");
return (this->_ev_list[index].filter == EVFILT_WRITE);
}
void webserv::Kqueue::test_error(int fd, const std::string &str)
{
if (fd < 0)
{
std::cerr << RED << str << " ";
perror("The following error occured: ");
std::cerr << RESET;
exit(EXIT_FAILURE);
}
}
/************************ GETTERS/SETTERS ************************/
struct kevent *webserv::Kqueue::get_event_list()
{
return (this->_ev_list);
}
int webserv::Kqueue::get_fd(int index)
{
if (this->_n_ev <= index)
this->test_error(-1, "Kqueue/get_ev_list function:");
return (this->_ev_list[index].ident);
}
void webserv::Kqueue::set_kqueue(int fd)
{
this->_kq = fd;
}

operating issues qustions - threads, processes etc. for the above code:

int S1 = 0;
int S2 = 0;
int x = 0;
int run = 1;
void Producer(void) {
while(run) {
while (S1 == S2);
x++;
__sync_synchronize();
S1 = S2;
__sync_synchronize();
}
}
void Consumer(void) {
while(run) {
while (S1 != S2);
x--;
__sync_synchronize();
S1 = !S2;
__sync_synchronize();
}
}
void* Worker(void *func) {
long func_id = (long)func & 0x1;
printf("%s %d\n",__func__, (int)func_id);
switch (func_id) {
case 0:
Producer();
break;
case 1:
Consumer();
break;
}
return NULL;
}
int main(int argc, char *argv[]) {
pthread_t t[argc];
pthread_attr_t at;
cpu_set_t cpuset;
int threads;
int i;
#define MAX_PROCESSORS 4 // Minimal processors is 2.
threads = argc > 1 ? (( atoi(argv[1]) < 4) ? atoi(argv[1]): MAX_PROCESSORS ) : 1;
for (i = 0;i < threads; i++){
CPU_ZERO(&cpuset);
CPU_SET(i, &cpuset);
pthread_attr_init(&at);
(&at, sizeof(cpuset), &cpuset);
if (pthread_create(&t[i], &at , Worker, (void *) (long)i) ) {
perror("pthread create 1 error\n"); }
}
do {
sleep(1);
} while(x < 0);
run = 0;
void *val;
for(i = 0; i < threads; i++)
pthread_join(t[i], &val);
printf("x=%d\n", x);
}
The questions:
In ex1.c (6.1), which of the following properties achieved:
(1) Mutual exclusion but not progress
(2) Progress but not mutual exclusion
(3) Neither mutual exclusion nor progress
(4) Both mutual exclusion and progress
Please explain?
1.2
To which arguments (in 6.1) is correct and which does not:
(1) always exits. when threads = 2 or threads <= 0
(2) always hangs. threads = 1 or thread > 2
Any help would be much appreeciated

My thread-safe queue code appears to work, any possible race conditions, deadlocks, or other design problems?

I am new to using condition_variables and unique_locks in C++. I am working on creating an event loop that polls two custom event-queues and a "boolean" (see integer acting as boolean), which can be acted upon by multiple sources.
I have a demo (below) that appears to work, which I would greatly appreciate if you can review and confirm if it follows the best practices for using unique_lock and condition_variables and any problems you foresee happening (race conditions, thread blocking, etc).
In ThreadSafeQueue::enqueue(...): are we unlocking twice by calling notify and having the unique_lock go out of scope?
In the method TheadSafeQueue::dequeueAll(): We assume it is being called by a method that has been notified (cond.notify), and therefore has been locked. Is there a better way to encapsulate this to keep the caller cleaner?
Do we need to make our class members volatile similar to this?
Is there a better way to mockup our situation that allows us to test if we've correctly implemented the locks? Perhaps without the sleep statements and automating the checking process?
ThreadSafeQueue.h:
#include <condition_variable>
#include <cstdint>
#include <iostream>
#include <mutex>
#include <vector>
template <class T>
class ThreadSafeQueue {
public:
ThreadSafeQueue(std::condition_variable* cond, std::mutex* unvrsl_m)
: ThreadSafeQueue(cond, unvrsl_m, 1) {}
ThreadSafeQueue(std::condition_variable* cond, std::mutex* unvrsl_m,
uint32_t capacity)
: cond(cond),
m(unvrsl_m),
head(0),
tail(0),
capacity(capacity),
buffer((T*)malloc(get_size() * sizeof(T))),
scratch_space((T*)malloc(get_size() * sizeof(T))) {}
std::condition_variable* cond;
~ThreadSafeQueue() {
free(scratch_space);
free(buffer);
}
void resize(uint32_t new_cap) {
std::unique_lock<std::mutex> lock(*m);
check_params_resize(new_cap);
free(scratch_space);
scratch_space = buffer;
buffer = (T*)malloc(sizeof(T) * new_cap);
copy_cyclical_queue();
free(scratch_space);
scratch_space = (T*)malloc(new_cap * sizeof(T));
tail = get_size();
head = 0;
capacity = new_cap;
}
void enqueue(const T& value) {
std::unique_lock<std::mutex> lock(*m);
resize();
buffer[tail++] = value;
if (tail == get_capacity()) {
tail = 0;
} else if (tail > get_capacity())
throw("Something went horribly wrong TSQ: 75");
cond->notify_one();
}
// Assuming m has already been locked by the caller...
void dequeueAll(std::vector<T>* vOut) {
if (get_size() == 0) return;
scratch_space = buffer;
copy_cyclical_queue();
vOut->insert(vOut->end(), buffer, buffer + get_size());
head = tail = 0;
}
// Const functions because they shouldn't be modifying the internal variables
// of the object
bool is_empty() const { return get_size() == 0; }
uint32_t get_size() const {
if (head == tail)
return 0;
else if (head < tail) {
// 1 2 3
// 0 1 2
// 1
// 0
return tail - head;
} else {
// 3 _ 1 2
// 0 1 2 3
// capacity-head + tail+1 = 4-2+0+1 = 2 + 1
return get_capacity() - head + tail + 1;
}
}
uint32_t get_capacity() const { return capacity; }
//---------------------------------------------------------------------------
private:
std::mutex* m;
uint32_t head;
uint32_t tail;
uint32_t capacity;
T* buffer;
T* scratch_space;
uint32_t get_next_empty_spot();
void copy_cyclical_queue() {
uint32_t size = get_size();
uint32_t cap = get_capacity();
if (size == 0) {
return; // because we have nothing to copy
}
if (head + size <= cap) {
// _ 1 2 3 ... index = 1, size = 3, 1+3 = 4 = capacity... only need 1 copy
memcpy(buffer, scratch_space + head, sizeof(T) * size);
} else {
// 5 1 2 3 4 ... index = 1, size = 5, 1+5 = 6 = capacity... need to copy
// 1-4 then 0-1
// copy number of bytes: front = 1, to (5-1 = 4 elements)
memcpy(buffer, scratch_space + head, sizeof(T) * (cap - head));
// just copy the bytes from the front up to the first element in the old
// array
memcpy(buffer + (cap - head), scratch_space, sizeof(T) * tail);
}
}
void check_params_resize(uint32_t new_cap) {
if (new_cap < get_size()) {
std::cerr << "ThreadSafeQueue: check_params_resize: size(" << get_size()
<< ") > new_cap(" << new_cap
<< ")... data "
"loss will occur if this happens. Prevented."
<< std::endl;
}
}
void resize() {
uint32_t new_cap;
uint32_t size = get_size();
uint32_t cap = get_capacity();
if (size + 1 >= cap - 1) {
std::cout << "RESIZE CALLED --- BAD" << std::endl;
new_cap = 2 * cap;
check_params_resize(new_cap);
free(scratch_space); // free existing (too small) scratch space
scratch_space = buffer; // transfer pointer over
buffer = (T*)malloc(sizeof(T) * new_cap); // allocate a bigger buffer
copy_cyclical_queue();
// move over everything with memcpy from scratch_space to buffer
free(scratch_space); // free what used to be the too-small buffer
scratch_space =
(T*)malloc(sizeof(T) * new_cap); // recreate scratch space
tail = size;
head = 0;
// since we're done with the old array... delete for memory management->
capacity = new_cap;
}
}
};
// Event Types
// keyboard/mouse
// network
// dirty flag
Main.cpp:
#include <unistd.h>
#include <cstdint>
#include <iostream>
#include <mutex>
#include <queue>
#include <sstream>
#include <thread>
#include "ThreadSafeQueue.h"
using namespace std;
void write_to_threadsafe_queue(ThreadSafeQueue<uint32_t> *q,
uint32_t startVal) {
uint32_t count = startVal;
while (true) {
q->enqueue(count);
cout << "Successfully enqueued: " << count << endl;
count += 2;
sleep(count);
}
}
void sleep_and_set_redraw(int *redraw, condition_variable *cond) {
while (true) {
sleep(3);
__sync_fetch_and_or(redraw, 1);
cond->notify_one();
}
}
void process_events(vector<uint32_t> *qOut, condition_variable *cond,
ThreadSafeQueue<uint32_t> *q1,
ThreadSafeQueue<uint32_t> *q2, int *redraw, mutex *m) {
while (true) {
unique_lock<mutex> lck(*m);
cond->wait(lck);
q1->dequeueAll(qOut);
q2->dequeueAll(qOut);
if (__sync_fetch_and_and(redraw, 0)) {
cout << "FLAG SET" << endl;
qOut->push_back(0);
}
for (auto a : *qOut) cout << a << "\t";
cout << endl;
cout << "PROCESSING: " << qOut->size() << endl;
qOut->clear();
}
}
void test_2_queues_and_bool() {
try {
condition_variable cond;
mutex m;
ThreadSafeQueue<uint32_t> q1(&cond, &m, 1024);
ThreadSafeQueue<uint32_t> q2(&cond, &m, 1024);
int redraw = 0;
vector<uint32_t> qOut;
thread t1(write_to_threadsafe_queue, &q1, 2);
thread t2(write_to_threadsafe_queue, &q2, 1);
thread t3(sleep_and_set_redraw, &redraw, &cond);
thread t4(process_events, &qOut, &cond, &q1, &q2, &redraw, &m);
t1.join();
t2.join();
t3.join();
t4.join();
} catch (system_error &e) {
cout << "MAIN TEST CRASHED" << e.what();
}
}
int main() { test_2_queues_and_bool(); }

Find the word in the stream?

Given an infinite stream of characters and a list L of strings, create a function that calls an external API when a word in L is recognized during the processing of the stream.
Example:
L = ["ok","test","one","try","trying"]
stream = a,b,c,o,k,d,e,f,t,r,y,i,n,g.............
The call to external API will happen when 'k' is encountered, again when the 'y' is encountered, and again at 'g'.
My idea:
Create trie out of the list and navigate the nodes as you read from stream in linear time. But there would be a bug if you just do simple trie search.
Assume you have words "abxyz" and "xyw" and your input is "abxyw".In this case you can't recognize "xyw" with trie.
So search should be modified as below:
let's take above use case "abxyw". We start the search and we find we have all the element till 'x'. Moment you get 'x' you have two options:
Check if the current element is equal to the head of trie and if it is equal to head of trie then call recursive search.
Continue till the end of current word. In this case for your given input it will return false but for the recursive search we started in point 1, it will return true.
Below is my modified search but I think it has bugs and can be improved. Any suggestions?
#define SIZE 26
struct tri{
int complete;
struct tri *child[SIZE];
};
void insert(char *c, struct tri **t)
{
struct tri *current = *t;
while(*c != '\0')
{
int i;
int letter = *c - 'a';
if(current->child[letter] == NULL) {
current->child[letter] = malloc(sizeof(*current));
memset(current->child[letter], 0, sizeof(struct tri));
}
current = current->child[letter];
c++;
}
current->complete = 1;
}
struct tri *t;
int flag = 0;
int found(char *c, struct tri *tt)
{
struct tri *current = tt;
if (current == NULL)
return 0;
while(*c != '\0')
{
int i;
int letter = *c - 'a';
/* if this is the first char then recurse from begining*/
if (t->child[letter] != NULL)
flag = found(c+1, t->child[letter]);
if (flag == 1)
return 1;
if(!flag && current->child[letter] == NULL) {
return 0;
}
current = current->child[letter];
c++;
}
return current->complete;
}
int main()
{
int i;
t = malloc(sizeof(*t));
t->complete = 0;
memset(t, 0, sizeof(struct tri));
insert("weathez", &t);
insert("eather", &t);
insert("weather", &t);
(1 ==found("weather", t))?printf("found\n"):printf("not found\n");
return 0;
}
What you want to do is exactly what Aho-Corasick algorithm does.
You can take a look at my Aho-Corasick implementation. It's contest-oriented, so maybe not focused on readability but I think it's quite clear:
typedef vector<int> VI;
struct Node {
int size;
Node *fail, *output;
VI id;
map<char, Node*> next;
};
typedef pair<Node*, Node*> P;
typedef map<char, Node*> MCP;
Node* root;
inline void init() {
root = new Node;
root->size = 0;
root->output = root->fail = NULL;
}
Node* add(string& s, int u, int c = 0, Node* p = root) {
if (p == NULL) {
p = new Node;
p->size = c;
p->fail = p->output = NULL;
}
if (c == s.size()) p->id.push_back(u);
else {
if (not p->next.count(s[c])) p->next[s[c]] = NULL;
p->next[s[c]] = add(s, u, c + 1, p->next[s[c]]);
}
return p;
}
void fill_fail_output() {
queue<pair<char, P> > Q;
for (MCP::iterator it=root->next.begin();
it!=root->next.end();++it)
Q.push(pair<char, P> (it->first, P(root, it->second)));
while (not Q.empty()) {
Node *pare = Q.front().second.first;
Node *fill = Q.front().second.second;
char c = Q.front().first; Q.pop();
while (pare != root && !pare->fail->next.count(c))
pare=pare->fail;
if (pare == root) fill->fail = root;
else fill->fail = pare->fail->next[c];
if (fill->fail->id.size() != 0)
fill->output = fill->fail;
else fill->output = fill->fail->output;
for (MCP::iterator it=fill->next.begin();
it!=fill->next.end();++it)
Q.push(pair<char,P>(it->first,P(fill,it->second)));
}
}
void match(int c, VI& id) {
for (int i = 0; i < id.size(); ++i) {
cout << "Matching of pattern " << id[i];
cout << " ended at " << c << endl;
}
}
void search(string& s) {
int i = 0, j = 0;
Node *p = root, *q;
while (j < s.size()) {
while (p->next.count(s[j])) {
p = p->next[s[j++]];
if (p->id.size() != 0) match(j - 1, p->id);
q = p->output;
while (q != NULL) {
match(j - 1, q->id);
q = q->output;
}
}
if (p != root) {
p = p->fail;
i = j - p->size;
}
else i = ++j;
}
}
void erase(Node* p = root) {
for (MCP::iterator it = p->next.begin();
it != p->next.end(); ++it)
erase(it->second);
delete p;
}
int main() {
init();
int n;
cin >> n;
for (int i = 0; i < n; ++i) {
string s;
cin >> s;
add(s, i);
}
fill_fail_output();
string text;
cin >> text;
search(text);
erase(root);
}

Resources