在许多编程语言中,可以使用多线程来实现并发执行任务。要让两个线程将特定时间戳插入表中,可以使用以下方法:
以下是一个使用Python和SQLite数据库的示例代码:
import threading
import sqlite3
import time
def insert_timestamp(thread_name, timestamp):
conn = sqlite3.connect('example.db')
cursor = conn.cursor()
cursor.execute("INSERT INTO timestamps (timestamp) VALUES (?)", (timestamp,))
conn.commit()
print(f"{thread_name} inserted {timestamp}")
conn.close()
def thread_function(thread_name):
timestamp = int(time.time())
insert_timestamp(thread_name, timestamp)
thread1 = threading.Thread(target=thread_function, args=("Thread 1",))
thread2 = threading.Thread(target=thread_function, args=("Thread 2",))
thread1.start()
thread2.start()
thread1.join()
thread2.join()
在这个示例中,我们创建了两个线程,每个线程都执行thread_function
函数。thread_function
函数会生成当前时间戳,并将其插入到名为timestamps
的表中。
请注意,这个示例仅适用于SQLite数据库。如果您使用的是其他类型的数据库,例如MySQL或PostgreSQL,则需要使用相应的Python库和连接字符串。
领取专属 10元无门槛券
手把手带您无忧上云