pthread not cancels

So this is my code.This should send infinite lines with word "test" while I am holding Middle Mouse.But when I press Middle mouse for 1 second it just goes on and not stops.

I just use std::cout << "test" to test if my code works.What I really want to do with program is: get infinite left mouse clicks while I hold middle mouse

I use -pthread in my compiler

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include <linux/input.h>
#include <fcntl.h>
#include <unistd.h>
#include <iostream>
#include <cstdlib>
#include <pthread.h>

int fd = open("/dev/input/event1", O_RDONLY);
int fm = open("/dev/input/event1", O_WRONLY | O_NONBLOCK);
struct input_event ev;
struct input_event sev;

void *click(void *a)
{
    while(1)
    {
		std::cout << "test" << std::endl;
		/*
		sev.code = 272;
		sev.type = 1;
		sev.value = 1;
		write(fm,&sev,sizeof(sev));
		sev.value = 0;
		write(fm,&sev,sizeof(sev));
		*/
    }
}

int main(int argc, char **argv)
{
    pthread_t thread[1];
    int enabled = 1;
    while (1)
    {
        read(fd, &ev, sizeof(struct input_event));
        std::cout << "key: " << ev.code << "state: " << ev.value << std::endl;
        if(ev.type == 1)
        {
			
            if(ev.code == 274 && enabled == 1 && ev.value == 1)
            {
                pthread_create(&thread[1], NULL, click, (void *)1);
            }
            if(ev.code == 274 && enabled == 1 && ev.value == 0)
            {
                pthread_cancel(thread[1]);
            }
            if(ev.code == 25)
            {
                if(enabled == 1)
                {
                    enabled = 0;
                }
                if(enabled == 0)
                {
                    enabled = 1;
                }
            }
        }
    }
}
Last edited on
1
2
3
pthread_t thread[1];
/...
pthread_create(&thread[1], 

Memory overrun. Why bother with the array at all?
Thanks I am using normal variable now,But it didn't changed the program's behavior.I still have the problem
The code's a bit messy with globals, magic numbers, ... I can see what you're trying to do, but ...

BTW, that's not how you do threading, you should have some controlled means of synchronising thread shutdowns. Stopping execution of code like that goes against C++ principles.
Topic archived. No new replies allowed.